@makeswift/runtime 0.28.7-canary.3 → 0.28.7-canary.4
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.
- package/dist/cjs/api/client.js +0 -8
- package/dist/cjs/api/client.js.map +1 -1
- package/dist/cjs/api/graphql-api-client.js +39 -0
- package/dist/cjs/api/graphql-api-client.js.map +1 -0
- package/dist/cjs/api-handler/handlers/manifest.js +1 -1
- package/dist/cjs/client/index.js +3 -3
- package/dist/cjs/components/builtin/Form/Form.js +2 -2
- package/dist/cjs/components/builtin/Form/Form.js.map +1 -1
- package/dist/cjs/runtimes/react/components/GoogleFontLink.js +2 -2
- package/dist/cjs/runtimes/react/components/GoogleFontLink.js.map +1 -1
- package/dist/cjs/runtimes/react/components/hooks/use-page-snippets.js +2 -2
- package/dist/cjs/runtimes/react/components/hooks/use-page-snippets.js.map +1 -1
- package/dist/cjs/runtimes/react/components/page/PageHead.js +2 -2
- package/dist/cjs/runtimes/react/components/page/PageHead.js.map +1 -1
- package/dist/cjs/runtimes/react/hooks/makeswift-api.js +10 -10
- package/dist/cjs/runtimes/react/hooks/makeswift-api.js.map +1 -1
- package/dist/cjs/runtimes/react/{host-api-client.js → hooks/use-api-resources-client.js} +9 -9
- package/dist/cjs/runtimes/react/hooks/use-api-resources-client.js.map +1 -0
- package/dist/cjs/runtimes/react/hooks/use-cache-data.js +2 -2
- package/dist/cjs/runtimes/react/hooks/use-cache-data.js.map +1 -1
- package/dist/cjs/runtimes/react/hooks/use-graphql-api-client.js +35 -0
- package/dist/cjs/runtimes/react/hooks/use-graphql-api-client.js.map +1 -0
- package/dist/cjs/runtimes/react/hooks/use-resource-resolver.js +3 -3
- package/dist/cjs/runtimes/react/hooks/use-resource-resolver.js.map +1 -1
- package/dist/cjs/runtimes/react/runtime-core.js +11 -6
- package/dist/cjs/runtimes/react/runtime-core.js.map +1 -1
- package/dist/cjs/state/middleware/makeswift-api-client-sync.js.map +1 -1
- package/dist/cjs/state/store.js +3 -3
- package/dist/cjs/state/store.js.map +1 -1
- package/dist/esm/api/client.js +0 -8
- package/dist/esm/api/client.js.map +1 -1
- package/dist/esm/api/graphql-api-client.js +15 -0
- package/dist/esm/api/graphql-api-client.js.map +1 -0
- package/dist/esm/api-handler/handlers/manifest.js +1 -1
- package/dist/esm/client/index.js +3 -3
- package/dist/esm/components/builtin/Form/Form.js +2 -2
- package/dist/esm/components/builtin/Form/Form.js.map +1 -1
- package/dist/esm/runtimes/react/components/GoogleFontLink.js +2 -2
- package/dist/esm/runtimes/react/components/GoogleFontLink.js.map +1 -1
- package/dist/esm/runtimes/react/components/hooks/use-page-snippets.js +2 -2
- package/dist/esm/runtimes/react/components/hooks/use-page-snippets.js.map +1 -1
- package/dist/esm/runtimes/react/components/page/PageHead.js +2 -2
- package/dist/esm/runtimes/react/components/page/PageHead.js.map +1 -1
- package/dist/esm/runtimes/react/hooks/makeswift-api.js +10 -10
- package/dist/esm/runtimes/react/hooks/makeswift-api.js.map +1 -1
- package/dist/esm/runtimes/react/hooks/use-api-resources-client.js +9 -0
- package/dist/esm/runtimes/react/hooks/use-api-resources-client.js.map +1 -0
- package/dist/esm/runtimes/react/hooks/use-cache-data.js +2 -2
- package/dist/esm/runtimes/react/hooks/use-cache-data.js.map +1 -1
- package/dist/esm/runtimes/react/hooks/use-graphql-api-client.js +11 -0
- package/dist/esm/runtimes/react/hooks/use-graphql-api-client.js.map +1 -0
- package/dist/esm/runtimes/react/hooks/use-resource-resolver.js +3 -3
- package/dist/esm/runtimes/react/hooks/use-resource-resolver.js.map +1 -1
- package/dist/esm/runtimes/react/runtime-core.js +11 -6
- package/dist/esm/runtimes/react/runtime-core.js.map +1 -1
- package/dist/esm/state/middleware/makeswift-api-client-sync.js.map +1 -1
- package/dist/esm/state/store.js +3 -3
- package/dist/esm/state/store.js.map +1 -1
- package/dist/types/api/client.d.ts +1 -5
- package/dist/types/api/client.d.ts.map +1 -1
- package/dist/types/api/graphql-api-client.d.ts +9 -0
- package/dist/types/api/graphql-api-client.d.ts.map +1 -0
- package/dist/types/runtimes/react/components/GoogleFontLink.d.ts.map +1 -1
- package/dist/types/runtimes/react/components/page/PageHead.d.ts.map +1 -1
- package/dist/types/runtimes/react/hooks/use-api-resources-client.d.ts +3 -0
- package/dist/types/runtimes/react/hooks/use-api-resources-client.d.ts.map +1 -0
- package/dist/types/runtimes/react/hooks/use-graphql-api-client.d.ts +3 -0
- package/dist/types/runtimes/react/hooks/use-graphql-api-client.d.ts.map +1 -0
- package/dist/types/runtimes/react/runtime-core.d.ts +2 -0
- package/dist/types/runtimes/react/runtime-core.d.ts.map +1 -1
- package/dist/types/state/middleware/makeswift-api-client-sync.d.ts +2 -2
- package/dist/types/state/middleware/makeswift-api-client-sync.d.ts.map +1 -1
- package/dist/types/state/store.d.ts +4 -4
- package/dist/types/state/store.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/runtimes/react/host-api-client.js.map +0 -1
- package/dist/esm/runtimes/react/host-api-client.js +0 -9
- package/dist/esm/runtimes/react/host-api-client.js.map +0 -1
- package/dist/types/runtimes/react/host-api-client.d.ts +0 -3
- package/dist/types/runtimes/react/host-api-client.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/runtimes/react/hooks/use-cache-data.ts"],"sourcesContent":["import { useMemo } from 'react'\nimport { type CacheData } from '../../../api/client'\nimport { updateAPIClientCache } from '../../../state/actions/internal/read-write-actions'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/runtimes/react/hooks/use-cache-data.ts"],"sourcesContent":["import { useMemo } from 'react'\nimport { type CacheData } from '../../../api/client'\nimport { updateAPIClientCache } from '../../../state/actions/internal/read-write-actions'\n\nimport { useApiResourcesClient } from './use-api-resources-client'\n\nexport function useCacheData(cacheData: CacheData) {\n const { store: apiStore } = useApiResourcesClient()\n\n // We perform cache hydration immediately on render - this is safe to do per\n // render because updating the API cache is idempotent. For precedence, see:\n //\n // https://github.com/TanStack/query/blob/8f9f183f11df3709a1a38c4efce1452788041f88/packages/react-query/src/HydrationBoundary.tsx#L41\n useMemo(() => apiStore.dispatch(updateAPIClientCache(cacheData)), [cacheData])\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwB;AAExB,gCAAqC;AAErC,sCAAsC;AAE/B,SAAS,aAAa,WAAsB;AACjD,QAAM,EAAE,OAAO,SAAS,QAAI,uDAAsB;AAMlD,4BAAQ,MAAM,SAAS,aAAS,gDAAqB,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC;AAC/E;","names":[]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
"use client";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
var use_graphql_api_client_exports = {};
|
|
21
|
+
__export(use_graphql_api_client_exports, {
|
|
22
|
+
useMakeswiftGraphQLApiClient: () => useMakeswiftGraphQLApiClient
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(use_graphql_api_client_exports);
|
|
25
|
+
var import_graphql_api_client = require("../../../api/graphql-api-client");
|
|
26
|
+
var import_use_react_runtime = require("./use-react-runtime");
|
|
27
|
+
function useMakeswiftGraphQLApiClient() {
|
|
28
|
+
const runtime = (0, import_use_react_runtime.useReactRuntime)();
|
|
29
|
+
return new import_graphql_api_client.MakeswiftGraphQLApiClient({ endpoint: runtime.graphqlApiEndpoint });
|
|
30
|
+
}
|
|
31
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
32
|
+
0 && (module.exports = {
|
|
33
|
+
useMakeswiftGraphQLApiClient
|
|
34
|
+
});
|
|
35
|
+
//# sourceMappingURL=use-graphql-api-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/runtimes/react/hooks/use-graphql-api-client.tsx"],"sourcesContent":["'use client'\n\nimport { MakeswiftGraphQLApiClient } from '../../../api/graphql-api-client'\n\nimport { useReactRuntime } from './use-react-runtime'\n\nexport function useMakeswiftGraphQLApiClient(): MakeswiftGraphQLApiClient {\n const runtime = useReactRuntime()\n return new MakeswiftGraphQLApiClient({ endpoint: runtime.graphqlApiEndpoint })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,gCAA0C;AAE1C,+BAAgC;AAEzB,SAAS,+BAA0D;AACxE,QAAM,cAAU,0CAAgB;AAChC,SAAO,IAAI,oDAA0B,EAAE,UAAU,QAAQ,mBAAmB,CAAC;AAC/E;","names":[]}
|
|
@@ -22,13 +22,13 @@ __export(use_resource_resolver_exports, {
|
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(use_resource_resolver_exports);
|
|
24
24
|
var import_react = require("react");
|
|
25
|
-
var import_host_api_client = require("../host-api-client");
|
|
26
25
|
var import_resource_resolver = require("../resource-resolver");
|
|
27
|
-
var
|
|
26
|
+
var import_use_api_resources_client = require("./use-api-resources-client");
|
|
28
27
|
var import_use_document_context = require("./use-document-context");
|
|
28
|
+
var import_use_store = require("./use-store");
|
|
29
29
|
function useResourceResolver() {
|
|
30
30
|
const store = (0, import_use_store.useStore)();
|
|
31
|
-
const apiClient = (0,
|
|
31
|
+
const apiClient = (0, import_use_api_resources_client.useApiResourcesClient)();
|
|
32
32
|
const documentKey = (0, import_use_document_context.useDocumentKey)();
|
|
33
33
|
const locale = (0, import_use_document_context.useDocumentLocale)();
|
|
34
34
|
return (0, import_react.useMemo)(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/runtimes/react/hooks/use-resource-resolver.ts"],"sourcesContent":["import { useMemo } from 'react'\nimport { type ResourceResolver } from '@makeswift/controls'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/runtimes/react/hooks/use-resource-resolver.ts"],"sourcesContent":["import { useMemo } from 'react'\nimport { type ResourceResolver } from '@makeswift/controls'\n\nimport { createResourceResolver } from '../resource-resolver'\n\nimport { useApiResourcesClient } from './use-api-resources-client'\nimport { useDocumentKey, useDocumentLocale } from './use-document-context'\nimport { useStore } from './use-store'\n\nexport function useResourceResolver(): ResourceResolver {\n const store = useStore()\n const apiClient = useApiResourcesClient()\n\n const documentKey = useDocumentKey()\n const locale = useDocumentLocale()\n\n return useMemo<ResourceResolver>(\n () =>\n createResourceResolver({\n store,\n apiClient,\n documentKey,\n locale,\n }),\n [store, apiClient, documentKey, locale],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwB;AAGxB,+BAAuC;AAEvC,sCAAsC;AACtC,kCAAkD;AAClD,uBAAyB;AAElB,SAAS,sBAAwC;AACtD,QAAM,YAAQ,2BAAS;AACvB,QAAM,gBAAY,uDAAsB;AAExC,QAAM,kBAAc,4CAAe;AACnC,QAAM,aAAS,+CAAkB;AAEjC,aAAO;AAAA,IACL,UACE,iDAAuB;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,IACH,CAAC,OAAO,WAAW,aAAa,MAAM;AAAA,EACxC;AACF;","names":[]}
|
|
@@ -65,16 +65,12 @@ class RuntimeCore {
|
|
|
65
65
|
getOrCreateStore({ siteVersion, locale }) {
|
|
66
66
|
const key = storeCacheKey({ siteVersion, locale });
|
|
67
67
|
const createStore = () => {
|
|
68
|
-
const
|
|
69
|
-
uri: new URL("graphql", this.apiOrigin).href,
|
|
70
|
-
fetch: this.fetch,
|
|
71
|
-
preloadedState: { siteVersion, locale }
|
|
72
|
-
});
|
|
68
|
+
const apiResourcesClient = this.createApiResourcesClient({ siteVersion, locale });
|
|
73
69
|
const isReadOnly = siteVersion == null;
|
|
74
70
|
return (0, import_store.configureReadWriteStore)({
|
|
75
71
|
name: `Runtime read-write store (site version: ${key})`,
|
|
76
72
|
appOrigin: this.appOrigin,
|
|
77
|
-
|
|
73
|
+
apiResourcesClient,
|
|
78
74
|
preloadedState: { ...this.protoStore.getState(), siteVersion, isReadOnly, locale }
|
|
79
75
|
});
|
|
80
76
|
};
|
|
@@ -107,6 +103,15 @@ class RuntimeCore {
|
|
|
107
103
|
getBreakpoints() {
|
|
108
104
|
return (0, import_read_only_state.getBreakpoints)(this.protoStore.getState());
|
|
109
105
|
}
|
|
106
|
+
get graphqlApiEndpoint() {
|
|
107
|
+
return new URL("graphql", this.apiOrigin).href;
|
|
108
|
+
}
|
|
109
|
+
createApiResourcesClient(preloadedState) {
|
|
110
|
+
return new import_client.MakeswiftHostApiClient({
|
|
111
|
+
fetch: this.fetch,
|
|
112
|
+
preloadedState
|
|
113
|
+
});
|
|
114
|
+
}
|
|
110
115
|
shouldUsePersistentStore(key) {
|
|
111
116
|
return !(0, import_is_server.isServer)() || this.requestKey !== void 0 && storeCacheKey(this.requestKey) === key;
|
|
112
117
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/runtimes/react/runtime-core.ts"],"sourcesContent":["import { type SerializableReplacementContext } from '@makeswift/controls'\n\nimport { MakeswiftHostApiClient } from '../../api/client'\nimport { type HttpFetch } from '../../state/api-client/fetch-api-resource'\nimport { type SiteVersion } from '../../api/site-version'\n\nimport {\n Breakpoints,\n BreakpointsInput,\n parseBreakpointsInput,\n} from '../../state/modules/breakpoints'\n\nimport { copyElementTree } from '../../state/ops/copy-element-tree'\n\nimport { getBreakpoints, type Element, type ElementData } from '../../state/read-only-state'\nimport {\n configureProtoStore,\n configureReadWriteStore,\n type ProtoStore,\n type Store,\n} from '../../state/store'\n\nimport { RefCountedMap } from '../../utils/ref-counted-map'\nimport { isServer } from '../../utils/is-server'\n\nexport type StoreKey = {\n siteVersion: SiteVersion | null\n locale: string | undefined\n}\n\nconst VERSION_TAG_LIVE = 'ref:live'\n\nexport class RuntimeCore {\n // The unowned entry TTL affects performance, not correctness. The TTL controls how long an unretained store stays\n // in the map. If an entry expires and is removed from the map before React commits, the store remains retained\n // via `<StoreContext.Provider>`. The only impact is that future lookups will create a new store instance instead of\n // reusing the existing one, reducing cache efficiency.\n private readonly activeStores = new RefCountedMap<string | null, Store>({\n unownedEntryTtlMs: 1000,\n // Checking on retain/release is sufficient on the client, and we don't need to check on get on the server\n // as the only scenario in which we add the store to the map is when the runtime is already bound to the\n // requested site version, which should be the only site version for which the store is requested\n ttlCheck: RefCountedMap.TTLCheck.ON_RETAIN | RefCountedMap.TTLCheck.ON_RELEASE,\n })\n\n readonly protoStore: ProtoStore\n readonly appOrigin: string\n readonly apiOrigin: string\n readonly requestKey: StoreKey | undefined\n readonly fetch: HttpFetch\n\n constructor({\n appOrigin = 'https://app.makeswift.com',\n apiOrigin = 'https://api.makeswift.com',\n breakpoints,\n requestKey,\n fetch,\n }: {\n appOrigin?: string\n apiOrigin?: string\n breakpoints?: BreakpointsInput\n requestKey?: StoreKey\n fetch: HttpFetch\n }) {\n this.appOrigin = validateOrigin(appOrigin, 'appOrigin')\n this.apiOrigin = validateOrigin(apiOrigin, 'apiOrigin')\n this.requestKey = requestKey\n this.fetch = fetch\n\n this.protoStore = configureProtoStore({\n name: 'Runtime proto-store',\n breakpoints: breakpoints ? parseBreakpointsInput(breakpoints) : undefined,\n })\n }\n\n getOrCreateStore({ siteVersion, locale }: StoreKey): Store {\n const key = storeCacheKey({ siteVersion, locale })\n\n const createStore = () => {\n //
|
|
1
|
+
{"version":3,"sources":["../../../../src/runtimes/react/runtime-core.ts"],"sourcesContent":["import { type SerializableReplacementContext } from '@makeswift/controls'\n\nimport { MakeswiftHostApiClient } from '../../api/client'\nimport { type HttpFetch } from '../../state/api-client/fetch-api-resource'\nimport { type SiteVersion } from '../../api/site-version'\n\nimport {\n Breakpoints,\n BreakpointsInput,\n parseBreakpointsInput,\n} from '../../state/modules/breakpoints'\n\nimport { copyElementTree } from '../../state/ops/copy-element-tree'\n\nimport { getBreakpoints, type Element, type ElementData } from '../../state/read-only-state'\nimport {\n configureProtoStore,\n configureReadWriteStore,\n type ProtoStore,\n type Store,\n} from '../../state/store'\n\nimport { RefCountedMap } from '../../utils/ref-counted-map'\nimport { isServer } from '../../utils/is-server'\n\nexport type StoreKey = {\n siteVersion: SiteVersion | null\n locale: string | undefined\n}\n\nconst VERSION_TAG_LIVE = 'ref:live'\n\nexport class RuntimeCore {\n // The unowned entry TTL affects performance, not correctness. The TTL controls how long an unretained store stays\n // in the map. If an entry expires and is removed from the map before React commits, the store remains retained\n // via `<StoreContext.Provider>`. The only impact is that future lookups will create a new store instance instead of\n // reusing the existing one, reducing cache efficiency.\n private readonly activeStores = new RefCountedMap<string | null, Store>({\n unownedEntryTtlMs: 1000,\n // Checking on retain/release is sufficient on the client, and we don't need to check on get on the server\n // as the only scenario in which we add the store to the map is when the runtime is already bound to the\n // requested site version, which should be the only site version for which the store is requested\n ttlCheck: RefCountedMap.TTLCheck.ON_RETAIN | RefCountedMap.TTLCheck.ON_RELEASE,\n })\n\n readonly protoStore: ProtoStore\n readonly appOrigin: string\n readonly apiOrigin: string\n readonly requestKey: StoreKey | undefined\n readonly fetch: HttpFetch\n\n constructor({\n appOrigin = 'https://app.makeswift.com',\n apiOrigin = 'https://api.makeswift.com',\n breakpoints,\n requestKey,\n fetch,\n }: {\n appOrigin?: string\n apiOrigin?: string\n breakpoints?: BreakpointsInput\n requestKey?: StoreKey\n fetch: HttpFetch\n }) {\n this.appOrigin = validateOrigin(appOrigin, 'appOrigin')\n this.apiOrigin = validateOrigin(apiOrigin, 'apiOrigin')\n this.requestKey = requestKey\n this.fetch = fetch\n\n this.protoStore = configureProtoStore({\n name: 'Runtime proto-store',\n breakpoints: breakpoints ? parseBreakpointsInput(breakpoints) : undefined,\n })\n }\n\n getOrCreateStore({ siteVersion, locale }: StoreKey): Store {\n const key = storeCacheKey({ siteVersion, locale })\n\n const createStore = () => {\n // API resources client includes an in-memory cache of the site's resources and thus also has to be versioned\n const apiResourcesClient = this.createApiResourcesClient({ siteVersion, locale })\n\n // TODO: we need to decouple editability from the site version; specifically, previewing\n // a draft version of the site should not lead to switching to the read-write state\n const isReadOnly = siteVersion == null\n\n return configureReadWriteStore({\n name: `Runtime read-write store (site version: ${key})`,\n appOrigin: this.appOrigin,\n apiResourcesClient,\n preloadedState: { ...this.protoStore.getState(), siteVersion, isReadOnly, locale },\n })\n }\n\n // On the server, stores are ephemeral by default so SSR does not retain them in a long-lived runtime.\n // The exception is a runtime that is already bound to the requested site version & locale, where we\n // can safely reuse the store across multiple root regions and benefit from the host API client's\n // in-memory cache.\n //\n // On the client, stores are reference-counted by site version so multiple root regions can share a store\n // instance, which preserves the pre-v0.17 per-site-version store behavior without requiring a separate\n // runtime per root.\n const usePersistentStore = this.shouldUsePersistentStore(key)\n return usePersistentStore ? this.activeStores.getOrCreate(key, createStore) : createStore()\n }\n\n retainStore({ siteVersion, locale }: StoreKey, store: Store): void {\n const key = storeCacheKey({ siteVersion, locale })\n\n if (!this.shouldUsePersistentStore(key)) {\n console.error('RuntimeCore: attempt to retain an ephemeral store', { key })\n return\n }\n\n if (this.activeStores.retain(key, store)) {\n store.startBreakpointWatch()\n }\n }\n\n releaseStore({ siteVersion, locale }: StoreKey, store: Store): void {\n const key = storeCacheKey({ siteVersion, locale })\n\n if (!this.shouldUsePersistentStore(key)) {\n console.error('RuntimeCore: attempt to release an ephemeral store', { key })\n return\n }\n\n if (this.activeStores.release(key, store)) {\n store.stopBreakpointWatch()\n }\n }\n\n copyElementTree(\n elementTree: ElementData,\n replacementContext: SerializableReplacementContext,\n ): Element {\n return copyElementTree(this.protoStore.getState(), elementTree, replacementContext)\n }\n\n getBreakpoints(): Breakpoints {\n return getBreakpoints(this.protoStore.getState())\n }\n\n get graphqlApiEndpoint(): string {\n return new URL('graphql', this.apiOrigin).href\n }\n\n private createApiResourcesClient(preloadedState: {\n siteVersion: SiteVersion | null\n locale: string | undefined\n }) {\n return new MakeswiftHostApiClient({\n fetch: this.fetch,\n preloadedState,\n })\n }\n\n private shouldUsePersistentStore(key: string): boolean {\n // don't persist stores on the server unless the runtime instance is bound to a request\n // and the requested store matches the request's site version and locale\n return !isServer() || (this.requestKey !== undefined && storeCacheKey(this.requestKey) === key)\n }\n}\n\nconst storeCacheKey = ({ siteVersion, locale }: StoreKey): string =>\n `${siteVersionTag(siteVersion)}/${locale ?? 'default'}`\n\nconst siteVersionTag = (siteVersion: SiteVersion | null): string =>\n siteVersion?.version ?? VERSION_TAG_LIVE\n\nfunction validateOrigin(url: string, name: string): string {\n try {\n return new URL(url).origin\n } catch {\n throw new Error(`The Makeswift runtime received an invalid \\`${name}\\` parameter: \"${url}\".`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAuC;AAIvC,yBAIO;AAEP,+BAAgC;AAEhC,6BAA+D;AAC/D,mBAKO;AAEP,6BAA8B;AAC9B,uBAAyB;AAOzB,MAAM,mBAAmB;AAElB,MAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,EAKN,eAAe,IAAI,qCAAoC;AAAA,IACtE,mBAAmB;AAAA;AAAA;AAAA;AAA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-client-sync.ts"],"sourcesContent":["import { type Middleware } from '@reduxjs/toolkit'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/state/middleware/makeswift-api-client-sync.ts"],"sourcesContent":["import { type Middleware } from '@reduxjs/toolkit'\n\nimport { ApiResourcesClient } from '../../api/api-resources-client'\n\nimport { type Action } from '../actions'\nimport { actionMiddleware } from '../toolkit'\nimport { type State, type Dispatch } from '../unified-state'\n\nexport function makeswiftApiClientSyncMiddleware(\n client: ApiResourcesClient,\n): Middleware<Dispatch, State, Dispatch> {\n return actionMiddleware(() => next => {\n return (action: Action) => {\n client.store.dispatch(action)\n\n return next(action)\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAAA,kBAAiC;AAG1B,SAAS,iCACd,QACuC;AACvC,aAAO,kCAAiB,MAAM,UAAQ;AACpC,WAAO,CAAC,WAAmB;AACzB,aAAO,MAAM,SAAS,MAAM;AAE5B,aAAO,KAAK,MAAM;AAAA,IACpB;AAAA,EACF,CAAC;AACH;","names":["import_toolkit"]}
|
package/dist/cjs/state/store.js
CHANGED
|
@@ -124,7 +124,7 @@ function withMixin(mixin) {
|
|
|
124
124
|
function configureReadWriteStore({
|
|
125
125
|
name,
|
|
126
126
|
appOrigin,
|
|
127
|
-
|
|
127
|
+
apiResourcesClient,
|
|
128
128
|
preloadedState
|
|
129
129
|
}) {
|
|
130
130
|
const readWriteMiddlewareRef = {
|
|
@@ -168,7 +168,7 @@ function configureReadWriteStore({
|
|
|
168
168
|
name,
|
|
169
169
|
preloadedState,
|
|
170
170
|
middleware: () => [
|
|
171
|
-
(0, import_makeswift_api_client_sync.makeswiftApiClientSyncMiddleware)(
|
|
171
|
+
(0, import_makeswift_api_client_sync.makeswiftApiClientSyncMiddleware)(apiResourcesClient),
|
|
172
172
|
conditionalReadWriteMiddleware(readWriteMiddlewareRef)
|
|
173
173
|
],
|
|
174
174
|
enhancers: () => new import_toolkit.Tuple(
|
|
@@ -180,7 +180,7 @@ function configureReadWriteStore({
|
|
|
180
180
|
})
|
|
181
181
|
),
|
|
182
182
|
withMixin({
|
|
183
|
-
|
|
183
|
+
apiResourcesClient,
|
|
184
184
|
loadReadWriteStateIfNeeded: async () => {
|
|
185
185
|
const { isReadOnly } = store.getState();
|
|
186
186
|
if (isReadOnly) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/state/store.ts"],"sourcesContent":["import {\n type Middleware,\n type StoreEnhancer,\n type MiddlewareAPI,\n Tuple,\n configureStore as configureReduxStore,\n combineReducers,\n compose,\n} from '@reduxjs/toolkit'\n\nimport { MakeswiftHostApiClient } from '../api/client'\n\nimport { actionMiddleware, middlewareOptions, devToolsConfig } from './toolkit'\nimport { BuilderActionTypes } from './builder-api/actions'\nimport { HostActionTypes } from './host-api'\n\nimport * as Breakpoints from './modules/breakpoints'\n\nimport { readOnlyElementTreeMiddleware } from './middleware/read-only-element-tree'\nimport { makeswiftApiClientSyncMiddleware } from './middleware/makeswift-api-client-sync'\nimport { type BreakpointWatch, breakpointWatchMixin } from './mixins/breakpoint-watch'\n\nimport { type Action } from './actions'\n\nimport { type State as ReadWriteState } from './read-write-state'\nimport * as ReadOnlyState from './read-only-state'\nimport {\n type State,\n type Dispatch,\n type ReadOnlyReducer,\n type ReadWriteDispatch,\n} from './unified-state'\n\nexport { type State } from './unified-state'\n\nconst configureStore = <Items extends readonly StoreEnhancer[] = []>({\n name,\n preloadedState,\n enhancers,\n middleware,\n}: {\n name: string\n preloadedState: Partial<State>\n enhancers: () => Tuple<Items>\n middleware?: () => Middleware[]\n}) => {\n const store = configureReduxStore({\n reducer: combineReducers(ReadOnlyState.reducers),\n preloadedState,\n\n middleware: getDefaultMiddleware =>\n getDefaultMiddleware(middlewareOptions).concat([\n readOnlyElementTreeMiddleware(),\n ...(middleware ? middleware() : []),\n ]),\n\n enhancers: getDefaultEnhancers => getDefaultEnhancers().concat(enhancers()),\n\n devTools: devToolsConfig({\n name: `${name} (${new Date().toISOString()})`,\n actionsDenylist: [\n HostActionTypes.BUILDER_POINTER_MOVE,\n BuilderActionTypes.HANDLE_POINTER_MOVE,\n BuilderActionTypes.ELEMENT_FROM_POINT_CHANGE,\n ],\n }),\n })\n\n return store\n}\n\nexport function configureProtoStore({\n name,\n breakpoints,\n}: {\n name: string\n breakpoints: Breakpoints.Breakpoints | undefined\n}) {\n return configureStore({\n name,\n preloadedState: {\n breakpoints: Breakpoints.getInitialState(breakpoints),\n },\n enhancers: () => new Tuple(),\n })\n}\n\nexport type ProtoStore = ReturnType<typeof configureProtoStore>\n\ntype ReadWriteMiddleware = ReturnType<\n typeof import('./middleware/read-write').createReadWriteMiddleware\n>\n\ntype ReadWriteMiddlewareRef = {\n current: ReadWriteMiddleware | null\n}\n\nexport function conditionalReadWriteMiddleware(\n middlewareRef: ReadWriteMiddlewareRef,\n): Middleware<Dispatch, State, Dispatch> {\n let readWriteActionBuffer: Action[] = []\n let middlewares: ReadWriteMiddleware | null = null\n let enhancedDispatch: Dispatch | null = null\n\n return actionMiddleware(({ dispatch, getState }) => next => {\n return (action: Action) => {\n const state = getState()\n\n if (middlewareRef.current == null) {\n if (!state.isReadOnly) {\n // because switching to the read-write state is an asynchronous operation,\n // we need to buffer all actions dispatched after the isReadOnly state is\n // set to false but before the read-write middleware is installed\n readWriteActionBuffer.push(action)\n }\n\n return next(action)\n }\n\n if (state.isReadOnly) {\n console.error('Read-write state mismatch', {\n isReadOnly: state.isReadOnly,\n middlewareRef: middlewareRef.current,\n siteVersion: state.siteVersion,\n })\n }\n\n // build and cache the enhanced dispatch chain when read-write middleware is installed\n if (enhancedDispatch == null || middlewares !== middlewareRef.current) {\n middlewares = middlewareRef.current\n\n const middlewareApi = { dispatch, getState } as MiddlewareAPI<\n ReadWriteDispatch,\n ReadWriteState\n >\n\n enhancedDispatch = compose<Dispatch>(...middlewares.map(mw => mw(middlewareApi)))(next)\n }\n\n // dispatch buffered actions, if any\n if (readWriteActionBuffer.length > 0) {\n const readWriteActions = [...readWriteActionBuffer]\n readWriteActionBuffer = []\n\n // Note that we're rerunning the actions through the entire middleware chain,\n // including the read-only middleware and the reducers, some of which have\n // already processed these actions once. This is safe to do because actions that\n // are run as part of page initialization are idempotent.\n for (const bufferedAction of readWriteActions) {\n enhancedDispatch(bufferedAction)\n }\n }\n\n return enhancedDispatch(action)\n }\n })\n}\n\nexport interface ReadWriteStateMixin {\n readonly hostApiClient: MakeswiftHostApiClient\n\n loadReadWriteStateIfNeeded(): Promise<() => void>\n}\n\nfunction withMixin<M extends {}>(mixin: M): StoreEnhancer<M> {\n return next => (reducer, preloadedState?) => ({\n ...next(reducer, preloadedState),\n ...mixin,\n })\n}\n\nexport function configureReadWriteStore({\n name,\n appOrigin,\n hostApiClient,\n preloadedState,\n}: {\n name: string\n appOrigin: string\n hostApiClient: MakeswiftHostApiClient\n preloadedState: Partial<State>\n}) {\n const readWriteMiddlewareRef: ReadWriteMiddlewareRef = {\n current: null,\n }\n\n let refCount = 0\n let readWriteCleanup: (() => void) | null = null\n let readWriteSetupPromise: Promise<void> | null = null\n\n const loadReadWriteState = async (): Promise<void> => {\n if (readWriteCleanup != null) {\n return\n }\n\n if (readWriteSetupPromise != null) {\n await readWriteSetupPromise\n return\n }\n\n readWriteSetupPromise = (async () => {\n // import all the modules needed for read-write mode before proceeding with\n // the setup to avoid race conditions when `setup` is called concurrently\n // in two different page regions\n const { BuilderAPIProxy } = await import('./builder-api/proxy')\n const { createRootReducer, setupBuilderProxy } = await import('./read-write-state')\n const { createReadWriteMiddleware } = await import('./middleware/read-write')\n\n // IMPORTANT: only synchronous code after this point\n\n // with all modules imported, check if another concurrent setup already\n // initialized the read-write middleware\n if (readWriteMiddlewareRef.current != null) {\n return\n }\n\n store.replaceReducer(createRootReducer() as ReadOnlyReducer)\n\n const builderProxy = new BuilderAPIProxy({ appOrigin })\n readWriteMiddlewareRef.current = createReadWriteMiddleware({ builderProxy })\n\n const dispatch = store.dispatch as ReadWriteDispatch\n const builderProxyCleanup = dispatch(setupBuilderProxy(builderProxy))\n\n readWriteCleanup = () => {\n readWriteMiddlewareRef.current = null\n builderProxyCleanup()\n }\n })()\n\n try {\n await readWriteSetupPromise\n } finally {\n readWriteSetupPromise = null\n }\n }\n\n const store = configureStore({\n name,\n preloadedState,\n\n middleware: () => [\n makeswiftApiClientSyncMiddleware(hostApiClient),\n conditionalReadWriteMiddleware(readWriteMiddlewareRef),\n ],\n\n enhancers: () =>\n new Tuple(\n withMixin<BreakpointWatch>(\n breakpointWatchMixin({\n dispatch: (...args: Parameters<Dispatch>) => store.dispatch(...args),\n getState: (): State => store.getState(),\n subscribe: (listener): VoidFunction => store.subscribe(listener),\n }),\n ),\n\n withMixin<ReadWriteStateMixin>({\n hostApiClient,\n loadReadWriteStateIfNeeded: async () => {\n const { isReadOnly } = store.getState()\n\n if (isReadOnly) {\n if (refCount > 0) {\n console.error('Read-write state mismatch', { isReadOnly, refCount })\n }\n\n return () => {}\n }\n\n await loadReadWriteState()\n refCount += 1\n\n let didCleanup = false\n return () => {\n if (didCleanup) {\n return\n }\n\n didCleanup = true\n refCount -= 1\n if (refCount === 0 && readWriteCleanup != null) {\n readWriteCleanup()\n readWriteCleanup = null\n }\n }\n },\n }),\n ),\n })\n\n return store\n}\n\nexport type Store = ReturnType<typeof configureReadWriteStore>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAQO;AAIP,IAAAA,kBAAoE;AACpE,qBAAmC;AACnC,sBAAgC;AAEhC,kBAA6B;AAE7B,oCAA8C;AAC9C,uCAAiD;AACjD,8BAA2D;AAK3D,oBAA+B;AAU/B,MAAM,iBAAiB,CAA8C;AAAA,EACnE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAKM;AACJ,QAAM,YAAQ,eAAAC,gBAAoB;AAAA,IAChC,aAAS,gCAAgB,cAAc,QAAQ;AAAA,IA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Y,CAAC;AAEpE,yBAAmB,MAAM;AACvB,+BAAuB,UAAU;AACjC,4BAAoB;AAAA,MACtB;AAAA,IACF,GAAG;AAEH,QAAI;AACF,YAAM;AAAA,IACR,UAAE;AACA,8BAAwB;AAAA,IAC1B;AAAA,EACF;AAEA,QAAM,QAAQ,eAAe;AAAA,IAC3B;AAAA,IACA;AAAA,IAEA,YAAY,MAAM;AAAA,UAChB,mEAAiC,aAAa;AAAA,MAC9C,+BAA+B,sBAAsB;AAAA,IACvD;AAAA,IAEA,WAAW,MACT,IAAI;AAAA,MACF;AAAA,YACE,8CAAqB;AAAA,UACnB,UAAU,IAAI,SAA+B,MAAM,SAAS,GAAG,IAAI;AAAA,UACnE,UAAU,MAAa,MAAM,SAAS;AAAA,UACtC,WAAW,CAAC,aAA2B,MAAM,UAAU,QAAQ;AAAA,QACjE,CAAC;AAAA,MACH;AAAA,MAEA,UAA+B;AAAA,QAC7B;AAAA,QACA,4BAA4B,YAAY;AACtC,gBAAM,EAAE,WAAW,IAAI,MAAM,SAAS;AAEtC,cAAI,YAAY;AACd,gBAAI,WAAW,GAAG;AAChB,sBAAQ,MAAM,6BAA6B,EAAE,YAAY,SAAS,CAAC;AAAA,YACrE;AAEA,mBAAO,MAAM;AAAA,YAAC;AAAA,UAChB;AAEA,gBAAM,mBAAmB;AACzB,sBAAY;AAEZ,cAAI,aAAa;AACjB,iBAAO,MAAM;AACX,gBAAI,YAAY;AACd;AAAA,YACF;AAEA,yBAAa;AACb,wBAAY;AACZ,gBAAI,aAAa,KAAK,oBAAoB,MAAM;AAC9C,+BAAiB;AACjB,iCAAmB;AAAA,YACrB;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACJ,CAAC;AAED,SAAO;AACT;","names":["import_toolkit","configureReduxStore"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/state/store.ts"],"sourcesContent":["import {\n type Middleware,\n type StoreEnhancer,\n type MiddlewareAPI,\n Tuple,\n configureStore as configureReduxStore,\n combineReducers,\n compose,\n} from '@reduxjs/toolkit'\n\nimport { ApiResourcesClient } from '../api/api-resources-client'\n\nimport { actionMiddleware, middlewareOptions, devToolsConfig } from './toolkit'\nimport { BuilderActionTypes } from './builder-api/actions'\nimport { HostActionTypes } from './host-api'\n\nimport * as Breakpoints from './modules/breakpoints'\n\nimport { readOnlyElementTreeMiddleware } from './middleware/read-only-element-tree'\nimport { makeswiftApiClientSyncMiddleware } from './middleware/makeswift-api-client-sync'\nimport { type BreakpointWatch, breakpointWatchMixin } from './mixins/breakpoint-watch'\n\nimport { type Action } from './actions'\n\nimport { type State as ReadWriteState } from './read-write-state'\nimport * as ReadOnlyState from './read-only-state'\nimport {\n type State,\n type Dispatch,\n type ReadOnlyReducer,\n type ReadWriteDispatch,\n} from './unified-state'\n\nexport { type State } from './unified-state'\n\nconst configureStore = <Items extends readonly StoreEnhancer[] = []>({\n name,\n preloadedState,\n enhancers,\n middleware,\n}: {\n name: string\n preloadedState: Partial<State>\n enhancers: () => Tuple<Items>\n middleware?: () => Middleware[]\n}) => {\n const store = configureReduxStore({\n reducer: combineReducers(ReadOnlyState.reducers),\n preloadedState,\n\n middleware: getDefaultMiddleware =>\n getDefaultMiddleware(middlewareOptions).concat([\n readOnlyElementTreeMiddleware(),\n ...(middleware ? middleware() : []),\n ]),\n\n enhancers: getDefaultEnhancers => getDefaultEnhancers().concat(enhancers()),\n\n devTools: devToolsConfig({\n name: `${name} (${new Date().toISOString()})`,\n actionsDenylist: [\n HostActionTypes.BUILDER_POINTER_MOVE,\n BuilderActionTypes.HANDLE_POINTER_MOVE,\n BuilderActionTypes.ELEMENT_FROM_POINT_CHANGE,\n ],\n }),\n })\n\n return store\n}\n\nexport function configureProtoStore({\n name,\n breakpoints,\n}: {\n name: string\n breakpoints: Breakpoints.Breakpoints | undefined\n}) {\n return configureStore({\n name,\n preloadedState: {\n breakpoints: Breakpoints.getInitialState(breakpoints),\n },\n enhancers: () => new Tuple(),\n })\n}\n\nexport type ProtoStore = ReturnType<typeof configureProtoStore>\n\ntype ReadWriteMiddleware = ReturnType<\n typeof import('./middleware/read-write').createReadWriteMiddleware\n>\n\ntype ReadWriteMiddlewareRef = {\n current: ReadWriteMiddleware | null\n}\n\nexport function conditionalReadWriteMiddleware(\n middlewareRef: ReadWriteMiddlewareRef,\n): Middleware<Dispatch, State, Dispatch> {\n let readWriteActionBuffer: Action[] = []\n let middlewares: ReadWriteMiddleware | null = null\n let enhancedDispatch: Dispatch | null = null\n\n return actionMiddleware(({ dispatch, getState }) => next => {\n return (action: Action) => {\n const state = getState()\n\n if (middlewareRef.current == null) {\n if (!state.isReadOnly) {\n // because switching to the read-write state is an asynchronous operation,\n // we need to buffer all actions dispatched after the isReadOnly state is\n // set to false but before the read-write middleware is installed\n readWriteActionBuffer.push(action)\n }\n\n return next(action)\n }\n\n if (state.isReadOnly) {\n console.error('Read-write state mismatch', {\n isReadOnly: state.isReadOnly,\n middlewareRef: middlewareRef.current,\n siteVersion: state.siteVersion,\n })\n }\n\n // build and cache the enhanced dispatch chain when read-write middleware is installed\n if (enhancedDispatch == null || middlewares !== middlewareRef.current) {\n middlewares = middlewareRef.current\n\n const middlewareApi = { dispatch, getState } as MiddlewareAPI<\n ReadWriteDispatch,\n ReadWriteState\n >\n\n enhancedDispatch = compose<Dispatch>(...middlewares.map(mw => mw(middlewareApi)))(next)\n }\n\n // dispatch buffered actions, if any\n if (readWriteActionBuffer.length > 0) {\n const readWriteActions = [...readWriteActionBuffer]\n readWriteActionBuffer = []\n\n // Note that we're rerunning the actions through the entire middleware chain,\n // including the read-only middleware and the reducers, some of which have\n // already processed these actions once. This is safe to do because actions that\n // are run as part of page initialization are idempotent.\n for (const bufferedAction of readWriteActions) {\n enhancedDispatch(bufferedAction)\n }\n }\n\n return enhancedDispatch(action)\n }\n })\n}\n\nexport interface ReadWriteStateMixin {\n readonly apiResourcesClient: ApiResourcesClient\n\n loadReadWriteStateIfNeeded(): Promise<() => void>\n}\n\nfunction withMixin<M extends {}>(mixin: M): StoreEnhancer<M> {\n return next => (reducer, preloadedState?) => ({\n ...next(reducer, preloadedState),\n ...mixin,\n })\n}\n\nexport function configureReadWriteStore({\n name,\n appOrigin,\n apiResourcesClient,\n preloadedState,\n}: {\n name: string\n appOrigin: string\n apiResourcesClient: ApiResourcesClient\n preloadedState: Partial<State>\n}) {\n const readWriteMiddlewareRef: ReadWriteMiddlewareRef = {\n current: null,\n }\n\n let refCount = 0\n let readWriteCleanup: (() => void) | null = null\n let readWriteSetupPromise: Promise<void> | null = null\n\n const loadReadWriteState = async (): Promise<void> => {\n if (readWriteCleanup != null) {\n return\n }\n\n if (readWriteSetupPromise != null) {\n await readWriteSetupPromise\n return\n }\n\n readWriteSetupPromise = (async () => {\n // import all the modules needed for read-write mode before proceeding with\n // the setup to avoid race conditions when `setup` is called concurrently\n // in two different page regions\n const { BuilderAPIProxy } = await import('./builder-api/proxy')\n const { createRootReducer, setupBuilderProxy } = await import('./read-write-state')\n const { createReadWriteMiddleware } = await import('./middleware/read-write')\n\n // IMPORTANT: only synchronous code after this point\n\n // with all modules imported, check if another concurrent setup already\n // initialized the read-write middleware\n if (readWriteMiddlewareRef.current != null) {\n return\n }\n\n store.replaceReducer(createRootReducer() as ReadOnlyReducer)\n\n const builderProxy = new BuilderAPIProxy({ appOrigin })\n readWriteMiddlewareRef.current = createReadWriteMiddleware({ builderProxy })\n\n const dispatch = store.dispatch as ReadWriteDispatch\n const builderProxyCleanup = dispatch(setupBuilderProxy(builderProxy))\n\n readWriteCleanup = () => {\n readWriteMiddlewareRef.current = null\n builderProxyCleanup()\n }\n })()\n\n try {\n await readWriteSetupPromise\n } finally {\n readWriteSetupPromise = null\n }\n }\n\n const store = configureStore({\n name,\n preloadedState,\n\n middleware: () => [\n makeswiftApiClientSyncMiddleware(apiResourcesClient),\n conditionalReadWriteMiddleware(readWriteMiddlewareRef),\n ],\n\n enhancers: () =>\n new Tuple(\n withMixin<BreakpointWatch>(\n breakpointWatchMixin({\n dispatch: (...args: Parameters<Dispatch>) => store.dispatch(...args),\n getState: (): State => store.getState(),\n subscribe: (listener): VoidFunction => store.subscribe(listener),\n }),\n ),\n\n withMixin<ReadWriteStateMixin>({\n apiResourcesClient,\n loadReadWriteStateIfNeeded: async () => {\n const { isReadOnly } = store.getState()\n\n if (isReadOnly) {\n if (refCount > 0) {\n console.error('Read-write state mismatch', { isReadOnly, refCount })\n }\n\n return () => {}\n }\n\n await loadReadWriteState()\n refCount += 1\n\n let didCleanup = false\n return () => {\n if (didCleanup) {\n return\n }\n\n didCleanup = true\n refCount -= 1\n if (refCount === 0 && readWriteCleanup != null) {\n readWriteCleanup()\n readWriteCleanup = null\n }\n }\n },\n }),\n ),\n })\n\n return store\n}\n\nexport type Store = ReturnType<typeof configureReadWriteStore>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAQO;AAIP,IAAAA,kBAAoE;AACpE,qBAAmC;AACnC,sBAAgC;AAEhC,kBAA6B;AAE7B,oCAA8C;AAC9C,uCAAiD;AACjD,8BAA2D;AAK3D,oBAA+B;AAU/B,MAAM,iBAAiB,CAA8C;AAAA,EACnE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAKM;AACJ,QAAM,YAAQ,eAAAC,gBAAoB;AAAA,IAChC,aAAS,gCAAgB,cAAc,QAAQ;AAAA,IAC/C;AAAA,IAEA,YAAY,0BACV,qBAAqB,iCAAiB,EAAE,OAAO;AAAA,UAC7C,6DAA8B;AAAA,MAC9B,GAAI,aAAa,WAAW,IAAI,CAAC;AAAA,IACnC,CAAC;AAAA,IAEH,WAAW,yBAAuB,oBAAoB,EAAE,OAAO,UAAU,CAAC;AAAA,IAE1E,cAAU,gCAAe;AAAA,MACvB,MAAM,GAAG,IAAI,MAAK,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,MAC1C,iBAAiB;AAAA,QACf,gCAAgB;AAAA,QAChB,kCAA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F;AAAA,YACE,8CAAqB;AAAA,UACnB,UAAU,IAAI,SAA+B,MAAM,SAAS,GAAG,IAAI;AAAA,UACnE,UAAU,MAAa,MAAM,SAAS;AAAA,UACtC,WAAW,CAAC,aAA2B,MAAM,UAAU,QAAQ;AAAA,QACjE,CAAC;AAAA,MACH;AAAA,MAEA,UAA+B;AAAA,QAC7B;AAAA,QACA,4BAA4B,YAAY;AACtC,gBAAM,EAAE,WAAW,IAAI,MAAM,SAAS;AAEtC,cAAI,YAAY;AACd,gBAAI,WAAW,GAAG;AAChB,sBAAQ,MAAM,6BAA6B,EAAE,YAAY,SAAS,CAAC;AAAA,YACrE;AAEA,mBAAO,MAAM;AAAA,YAAC;AAAA,UAChB;AAEA,gBAAM,mBAAmB;AACzB,sBAAY;AAEZ,cAAI,aAAa;AACjB,iBAAO,MAAM;AACX,gBAAI,YAAY;AACd;AAAA,YACF;AAEA,yBAAa;AACb,wBAAY;AACZ,gBAAI,aAAa,KAAK,oBAAoB,MAAM;AAC9C,+BAAiB;AACjB,iCAAmB;AAAA,YACrB;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACJ,CAAC;AAED,SAAO;AACT;","names":["import_toolkit","configureReduxStore"]}
|
package/dist/esm/api/client.js
CHANGED
|
@@ -3,22 +3,17 @@ import { configureClientStore } from "../state/api-client/client-store";
|
|
|
3
3
|
import {
|
|
4
4
|
APIResourceType
|
|
5
5
|
} from "./types";
|
|
6
|
-
import { GraphQLClient } from "./graphql/client";
|
|
7
|
-
import { CreateTableRecordMutation } from "./graphql/documents";
|
|
8
6
|
import { ApiResourcesClient } from "./api-resources-client";
|
|
9
7
|
import { CacheData } from "./api-resources-client";
|
|
10
8
|
class MakeswiftHostApiClient extends ApiResourcesClient {
|
|
11
|
-
graphqlClient;
|
|
12
9
|
fetch;
|
|
13
10
|
constructor({
|
|
14
|
-
uri,
|
|
15
11
|
fetch,
|
|
16
12
|
preloadedState
|
|
17
13
|
}) {
|
|
18
14
|
super({
|
|
19
15
|
store: configureClientStore({ preloadedState })
|
|
20
16
|
});
|
|
21
|
-
this.graphqlClient = new GraphQLClient(uri);
|
|
22
17
|
this.fetch = fetch;
|
|
23
18
|
}
|
|
24
19
|
async fetchSwatch(swatchId) {
|
|
@@ -56,9 +51,6 @@ class MakeswiftHostApiClient extends ApiResourcesClient {
|
|
|
56
51
|
async fetchTable(tableId) {
|
|
57
52
|
return await this.store.dispatch(fetchAPIResource(APIResourceType.Table, tableId, this.fetch));
|
|
58
53
|
}
|
|
59
|
-
async createTableRecord(tableId, columns) {
|
|
60
|
-
await this.graphqlClient.request(CreateTableRecordMutation, { input: { data: { tableId, columns } } });
|
|
61
|
-
}
|
|
62
54
|
}
|
|
63
55
|
export {
|
|
64
56
|
CacheData,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/api/client.ts"],"sourcesContent":["import { type State as ApiClientState } from '../state/api-client/state'\nimport { type HttpFetch, fetchAPIResource } from '../state/api-client/fetch-api-resource'\nimport { configureClientStore } from '../state/api-client/client-store'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type PagePathnameSlice,\n type Swatch,\n type Table,\n type Typography,\n APIResourceType,\n} from './types'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/api/client.ts"],"sourcesContent":["import { type State as ApiClientState } from '../state/api-client/state'\nimport { type HttpFetch, fetchAPIResource } from '../state/api-client/fetch-api-resource'\nimport { configureClientStore } from '../state/api-client/client-store'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type PagePathnameSlice,\n type Swatch,\n type Table,\n type Typography,\n APIResourceType,\n} from './types'\n\nimport { ApiResourcesClient } from './api-resources-client'\n\nexport { CacheData } from './api-resources-client'\n\n/**\n * NOTE(miguel): This \"client\" is used to fetch Makeswift API resources needed for the host. For\n * example, swatches, files, typographies, etc. Ideally it's internal to the runtime and is only\n * used by controls to transform API references to API resources.\n *\n * Moreover, its use should be reserved for the builder only, since for live pages all Makeswift\n * API resources should be embedded in the \"page snapshot\". In the builder, this client serves the\n * purpose of sending requests for API resources and keeping a cache so that changes that happen in\n * the builder, like modifying a swatch, can be sent via `postMessage` to the host and the cache can\n * immediately update the value and re-render.\n *\n * Furthermore, the API resources requested shouldn't be requested directly from the Makeswift API\n * as that would require those resources to not be authenticated since the requests come from the\n * browser when running the host. Instead, the requests should go to the host directly, at the\n * Makeswift API endpoint (i.g., `/api/makeswift/[...makeswift]` dynamic route) where the host's\n * API key can be used, securely, in the server. For this reason, this client should really be a\n * client of the host's API, not Makeswift's, intended to build and continuously maintain a realtime\n * snapshot for use in the builder, not the lives pages.\n */\nexport class MakeswiftHostApiClient extends ApiResourcesClient {\n readonly fetch: HttpFetch\n\n constructor({\n fetch,\n preloadedState,\n }: {\n fetch: HttpFetch\n preloadedState: Partial<ApiClientState>\n }) {\n super({\n store: configureClientStore({ preloadedState }),\n })\n\n this.fetch = fetch\n }\n\n async fetchSwatch(swatchId: string): Promise<Swatch | null> {\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Swatch, swatchId, this.fetch))\n }\n\n async fetchFile(fileId: string): Promise<File | null> {\n return await this.store.dispatch(fetchAPIResource(APIResourceType.File, fileId, this.fetch))\n }\n\n async fetchTypography(typographyId: string): Promise<Typography | null> {\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.Typography, typographyId, this.fetch),\n )\n }\n\n async fetchGlobalElement(globalElementId: string): Promise<GlobalElement | null> {\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.GlobalElement, globalElementId, this.fetch),\n )\n }\n\n async fetchLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): Promise<LocalizedGlobalElement | null> {\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.LocalizedGlobalElement, globalElementId, this.fetch, locale),\n )\n }\n\n async fetchPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): Promise<PagePathnameSlice | null> {\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.PagePathnameSlice, pageId, this.fetch, locale),\n )\n }\n\n async fetchTable(tableId: string): Promise<Table | null> {\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Table, tableId, this.fetch))\n }\n}\n"],"mappings":"AACA,SAAyB,wBAAwB;AACjD,SAAS,4BAA4B;AAErC;AAAA,EAQE;AAAA,OACK;AAEP,SAAS,0BAA0B;AAEnC,SAAS,iBAAiB;AAqBnB,MAAM,+BAA+B,mBAAmB;AAAA,EACpD;AAAA,EAET,YAAY;AAAA,IACV;AAAA,IACA;AAAA,EACF,GAGG;AACD,UAAM;AAAA,MACJ,OAAO,qBAAqB,EAAE,eAAe,CAAC;AAAA,IAChD,CAAC;AAED,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,YAAY,UAA0C;AAC1D,WAAO,MAAM,KAAK,MAAM,SAAS,iBAAiB,gBAAgB,QAAQ,UAAU,KAAK,KAAK,CAAC;AAAA,EACjG;AAAA,EAEA,MAAM,UAAU,QAAsC;AACpD,WAAO,MAAM,KAAK,MAAM,SAAS,iBAAiB,gBAAgB,MAAM,QAAQ,KAAK,KAAK,CAAC;AAAA,EAC7F;AAAA,EAEA,MAAM,gBAAgB,cAAkD;AACtE,WAAO,MAAM,KAAK,MAAM;AAAA,MACtB,iBAAiB,gBAAgB,YAAY,cAAc,KAAK,KAAK;AAAA,IACvE;AAAA,EACF;AAAA,EAEA,MAAM,mBAAmB,iBAAwD;AAC/E,WAAO,MAAM,KAAK,MAAM;AAAA,MACtB,iBAAiB,gBAAgB,eAAe,iBAAiB,KAAK,KAAK;AAAA,IAC7E;AAAA,EACF;AAAA,EAEA,MAAM,4BAA4B;AAAA,IAChC;AAAA,IACA;AAAA,EACF,GAG2C;AACzC,WAAO,MAAM,KAAK,MAAM;AAAA,MACtB,iBAAiB,gBAAgB,wBAAwB,iBAAiB,KAAK,OAAO,MAAM;AAAA,IAC9F;AAAA,EACF;AAAA,EAEA,MAAM,uBAAuB;AAAA,IAC3B;AAAA,IACA;AAAA,EACF,GAGsC;AACpC,WAAO,MAAM,KAAK,MAAM;AAAA,MACtB,iBAAiB,gBAAgB,mBAAmB,QAAQ,KAAK,OAAO,MAAM;AAAA,IAChF;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,SAAwC;AACvD,WAAO,MAAM,KAAK,MAAM,SAAS,iBAAiB,gBAAgB,OAAO,SAAS,KAAK,KAAK,CAAC;AAAA,EAC/F;AACF;","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { GraphQLClient } from "./graphql/client";
|
|
2
|
+
import { CreateTableRecordMutation } from "./graphql/documents";
|
|
3
|
+
class MakeswiftGraphQLApiClient {
|
|
4
|
+
graphqlClient;
|
|
5
|
+
constructor({ endpoint }) {
|
|
6
|
+
this.graphqlClient = new GraphQLClient(endpoint);
|
|
7
|
+
}
|
|
8
|
+
async createTableRecord(tableId, columns) {
|
|
9
|
+
await this.graphqlClient.request(CreateTableRecordMutation, { input: { data: { tableId, columns } } });
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
MakeswiftGraphQLApiClient
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=graphql-api-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/api/graphql-api-client.ts"],"sourcesContent":["import { GraphQLClient } from './graphql/client'\nimport { CreateTableRecordMutation } from './graphql/documents'\nimport {\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables,\n} from './graphql/generated/types'\n\nexport class MakeswiftGraphQLApiClient {\n readonly graphqlClient: GraphQLClient\n\n constructor({ endpoint }: { endpoint: string }) {\n this.graphqlClient = new GraphQLClient(endpoint)\n }\n\n async createTableRecord(tableId: string, columns: any): Promise<void> {\n await this.graphqlClient.request<\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables\n >(CreateTableRecordMutation, { input: { data: { tableId, columns } } })\n }\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AAMnC,MAAM,0BAA0B;AAAA,EAC5B;AAAA,EAET,YAAY,EAAE,SAAS,GAAyB;AAC9C,SAAK,gBAAgB,IAAI,cAAc,QAAQ;AAAA,EACjD;AAAA,EAEA,MAAM,kBAAkB,SAAiB,SAA6B;AACpE,UAAM,KAAK,cAAc,QAGvB,2BAA2B,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,QAAQ,EAAE,EAAE,CAAC;AAAA,EACxE;AACF;","names":[]}
|
|
@@ -8,7 +8,7 @@ async function manifestHandler(req, { apiKey, manifest }) {
|
|
|
8
8
|
return ApiResponse.json({ message: "Unauthorized" }, { status: 401 });
|
|
9
9
|
}
|
|
10
10
|
return ApiResponse.json({
|
|
11
|
-
version: "0.28.7-canary.
|
|
11
|
+
version: "0.28.7-canary.4",
|
|
12
12
|
interactionMode: true,
|
|
13
13
|
clientSideNavigation: false,
|
|
14
14
|
elementFromPoint: false,
|
package/dist/esm/client/index.js
CHANGED
|
@@ -198,7 +198,7 @@ Received "${apiKey}" instead.`
|
|
|
198
198
|
}
|
|
199
199
|
this.apiKey = apiKey;
|
|
200
200
|
this.graphqlClient = new GraphQLClient(new URL("graphql", runtime.apiOrigin).href, {
|
|
201
|
-
"makeswift-runtime-version": "0.28.7-canary.
|
|
201
|
+
"makeswift-runtime-version": "0.28.7-canary.4"
|
|
202
202
|
});
|
|
203
203
|
this.runtime = runtime;
|
|
204
204
|
}
|
|
@@ -210,7 +210,7 @@ Received "${apiKey}" instead.`
|
|
|
210
210
|
const requestHeaders = new Headers({
|
|
211
211
|
"x-api-key": this.apiKey,
|
|
212
212
|
"makeswift-site-api-key": this.apiKey,
|
|
213
|
-
"makeswift-runtime-version": "0.28.7-canary.
|
|
213
|
+
"makeswift-runtime-version": "0.28.7-canary.4"
|
|
214
214
|
});
|
|
215
215
|
if (siteVersion?.token) {
|
|
216
216
|
requestUrl.searchParams.set("version", siteVersion.version);
|
|
@@ -937,7 +937,7 @@ Received "${apiKey}" instead.`
|
|
|
937
937
|
headers: {
|
|
938
938
|
"x-api-key": this.apiKey,
|
|
939
939
|
"makeswift-site-api-key": this.apiKey,
|
|
940
|
-
"makeswift-runtime-version": "0.28.7-canary.
|
|
940
|
+
"makeswift-runtime-version": "0.28.7-canary.4",
|
|
941
941
|
"content-type": "application/json"
|
|
942
942
|
},
|
|
943
943
|
body: JSON.stringify({ token }),
|
|
@@ -25,7 +25,7 @@ import { getBox } from "../../../state/modules/read-write/box-models";
|
|
|
25
25
|
import { useTableFormFieldRefs } from "../../hooks/useTableFormFieldRefs";
|
|
26
26
|
import { cx } from "@emotion/css";
|
|
27
27
|
import { useResponsiveGridItem, useResponsiveStyle } from "../../utils/responsive-style";
|
|
28
|
-
import {
|
|
28
|
+
import { useMakeswiftGraphQLApiClient } from "../../../runtimes/react/hooks/use-graphql-api-client";
|
|
29
29
|
import { useStyle } from "../../../runtimes/react/use-style";
|
|
30
30
|
import { useTable } from "../../../runtimes/react/hooks/makeswift-api";
|
|
31
31
|
const LOCAL_STORAGE_NAMESPACE = "@@makeswift/components/form";
|
|
@@ -181,7 +181,7 @@ const Form = forwardRef(function Form2({
|
|
|
181
181
|
const fields = useMemo(() => fieldsProp?.fields ?? [], [fieldsProp]);
|
|
182
182
|
const grid = useMemo(() => fieldsProp?.grid ?? [], [fieldsProp]);
|
|
183
183
|
const table = useTable(tableId ?? null);
|
|
184
|
-
const client =
|
|
184
|
+
const client = useMakeswiftGraphQLApiClient();
|
|
185
185
|
const [refEl, setRefEl] = useState(null);
|
|
186
186
|
const [propControllers, setPropControllers] = useState(null);
|
|
187
187
|
const [initialValues, setInitialValues] = useState(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/components/builtin/Form/Form.tsx"],"sourcesContent":["'use client'\n\nimport {\n useState,\n useEffect,\n useRef,\n useMemo,\n forwardRef,\n ComponentPropsWithoutRef,\n Ref,\n useImperativeHandle,\n ForwardedRef,\n} from 'react'\nimport { Formik, getIn } from 'formik'\n\nimport { Check12 } from '../../icons/Check12'\n\nimport { getSizeHeight as getInputSizeHeight } from './components/Field/components/Input'\n\nimport {\n Size,\n Sizes,\n Provider as FormContextProvider,\n Shape,\n Contrast,\n Alignment,\n Alignments,\n} from './context/FormContext'\nimport Placeholder from './components/Placeholder'\nimport Field from './components/Field'\nimport Spinner from './components/Spinner'\nimport Button from '../Button'\nimport type { TableColumn } from './types'\nimport { Link } from '../../shared/Link'\nimport { getBox, type BoxModelHandle } from '../../../state/modules/read-write/box-models'\nimport { PropControllersHandle } from '../../../state/modules/prop-controller-handles'\nimport { DescriptorsPropControllers } from '../../../prop-controllers/instances'\nimport { useTableFormFieldRefs } from '../../hooks/useTableFormFieldRefs'\nimport { cx } from '@emotion/css'\nimport { useResponsiveGridItem, useResponsiveStyle } from '../../utils/responsive-style'\nimport { type ResponsiveColor } from '../../utils/types'\n\nimport { useMakeswiftHostApiClient } from '../../../runtimes/react/host-api-client'\nimport { useStyle } from '../../../runtimes/react/use-style'\nimport { useTable } from '../../../runtimes/react/hooks/makeswift-api'\nimport {\n type LinkData,\n type ResponsiveGapData,\n type ResponsiveLengthData,\n type ResponsiveIconRadioGroupValue,\n type ResponsiveTextStyleData,\n type ResponsiveSelectValue,\n type ResponsiveValue,\n type TableFormFieldsData,\n type TableFormFieldsDescriptor,\n} from '@makeswift/prop-controllers'\n\nconst LOCAL_STORAGE_NAMESPACE = '@@makeswift/components/form'\n\nfunction getSizeFontSize(size: Size): number {\n switch (size) {\n case Sizes.SMALL:\n return 12\n\n case Sizes.MEDIUM:\n return 14\n\n case Sizes.LARGE:\n return 18\n\n default:\n throw new Error(`Invalid form size \"${size}\"`)\n }\n}\n\ntype Props = {\n id?: string\n tableId?: string\n fields?: TableFormFieldsData\n submitLink?: LinkData\n gap?: ResponsiveGapData\n shape?: ResponsiveIconRadioGroupValue<Shape>\n size?: ResponsiveIconRadioGroupValue<Size>\n contrast?: ResponsiveIconRadioGroupValue<Contrast>\n labelTextStyle?: ResponsiveTextStyleData\n labelTextColor?: ResponsiveColor | null\n submitTextStyle?: ResponsiveTextStyleData\n brandColor?: ResponsiveColor | null\n submitTextColor?: ResponsiveColor | null\n submitLabel?: string\n submitVariant?: ResponsiveSelectValue<\n 'flat' | 'outline' | 'shadow' | 'clear' | 'blocky' | 'bubbly' | 'skewed'\n >\n submitWidth?: ResponsiveLengthData\n submitAlignment?: ResponsiveIconRadioGroupValue<Alignment>\n width?: string\n margin?: string\n}\n\ntype GridFormBaseProps = { size?: Props['size'] }\n\ntype GridFormProps = GridFormBaseProps &\n Omit<ComponentPropsWithoutRef<'form'>, keyof GridFormBaseProps>\n\nconst GridForm = forwardRef(function GridFrom(\n { className, size, ...restOfProps }: GridFormProps,\n ref: ForwardedRef<HTMLFormElement>,\n) {\n return (\n <form\n {...restOfProps}\n ref={ref}\n className={cx(\n useStyle({ display: 'flex', flexWrap: 'wrap', width: '100%' }),\n useStyle(\n useResponsiveStyle([size] as const, ([size = Sizes.MEDIUM]) => ({\n fontSize: getSizeFontSize(size),\n })),\n ),\n className,\n )}\n />\n )\n})\n\ntype GridItemBaseProps = {\n grid: ResponsiveValue<{ spans: number[][]; count: number }>\n index: number\n rowGap: Props['gap']\n columnGap: Props['gap']\n}\n\ntype GridItemProps = GridItemBaseProps &\n Omit<ComponentPropsWithoutRef<'div'>, keyof GridItemBaseProps>\n\nconst GridItem = forwardRef(function GridItem(\n { className, grid, index, rowGap, columnGap, ...restOfProps }: GridItemProps,\n ref: ForwardedRef<HTMLDivElement>,\n) {\n return (\n <div\n {...restOfProps}\n ref={ref}\n className={cx(\n useStyle({ alignSelf: 'flex-end', flexDirection: 'column' }),\n useStyle(useResponsiveGridItem({ grid, index, rowGap, columnGap })),\n className,\n )}\n />\n )\n})\n\nfunction getAlignmentMargin(alignment: Alignment): string {\n switch (alignment) {\n case Alignments.LEFT:\n return '0 auto 0 0'\n case Alignments.RIGHT:\n return '0 0 0 auto'\n default:\n return '0 auto'\n }\n}\n\ntype StyledButtonBaseProps = { size?: Props['size']; alignment?: Props['submitAlignment'] }\n\ntype StyledButtonProps = StyledButtonBaseProps &\n Omit<ComponentPropsWithoutRef<typeof Button>, keyof StyledButtonBaseProps>\n\nfunction StyledButton({ className, size, alignment, ...restOfProps }: StyledButtonProps) {\n return (\n <Button\n {...restOfProps}\n as=\"button\"\n className={cx(\n useStyle({ display: 'flex', alignItems: 'center', justifyContent: 'center' }),\n useStyle(\n useResponsiveStyle(\n [size, alignment] as const,\n ([size = Sizes.MEDIUM, alignment = Alignments.CENTER]) => ({\n minHeight: getInputSizeHeight(size),\n maxHeight: getInputSizeHeight(size),\n margin: getAlignmentMargin(alignment),\n paddingTop: 0,\n paddingBottom: 0,\n }),\n ),\n ),\n className,\n )}\n />\n )\n}\n\nfunction ErrorContainer({ className, ...restOfProps }: ComponentPropsWithoutRef<'div'>) {\n return (\n <div\n {...restOfProps}\n className={cx(\n useStyle({\n padding: '8px 16px',\n backgroundColor: '#f19eb9',\n borderRadius: 4,\n marginTop: 16,\n }),\n className,\n )}\n />\n )\n}\n\nfunction IconContainer({ className, ...restOfProps }: ComponentPropsWithoutRef<'div'>) {\n return <div {...restOfProps} className={cx(useStyle({ fill: 'currentColor' }), className)} />\n}\n\nfunction ErrorMessage({ className, ...restOfProps }: ComponentPropsWithoutRef<'p'>) {\n return (\n <p\n {...restOfProps}\n className={cx(\n useStyle({ fontSize: 12, margin: '8px 0', color: 'rgba(127, 0, 0, 0.95)' }),\n className,\n )}\n />\n )\n}\n\nfunction getTableColumnDefaultValue(tableColumn: TableColumn) {\n switch (tableColumn.__typename) {\n case 'CheckboxTableColumn':\n return false\n\n case 'MultipleSelectTableColumn':\n return []\n\n case 'SingleLineTextTableColumn':\n case 'LongTextTableColumn':\n case 'SingleSelectTableColumn':\n case 'PhoneNumberTableColumn':\n case 'EmailTableColumn':\n case 'URLTableColumn':\n case 'NumberTableColumn':\n default:\n return ''\n }\n}\n\ntype Column = { columnId: string; data: Record<string, any> }\ntype Fields = Record<string, string | string[] | boolean>\n\ntype Descriptors = { fields?: TableFormFieldsDescriptor }\n\nconst Form = forwardRef(function Form(\n {\n id,\n tableId,\n fields: fieldsProp,\n submitLabel = 'Submit',\n submitLink,\n shape,\n size,\n contrast,\n brandColor,\n gap,\n width,\n margin,\n submitTextStyle,\n submitVariant,\n submitTextColor,\n submitWidth,\n submitAlignment,\n labelTextStyle,\n labelTextColor,\n }: Props,\n ref: Ref<BoxModelHandle & PropControllersHandle<Descriptors>>,\n) {\n const fields = useMemo(() => fieldsProp?.fields ?? [], [fieldsProp])\n const grid = useMemo(() => fieldsProp?.grid ?? [], [fieldsProp])\n const table = useTable(tableId ?? null)\n const client = useMakeswiftHostApiClient()\n const [refEl, setRefEl] = useState<HTMLElement | null>(null)\n const [propControllers, setPropControllers] =\n useState<DescriptorsPropControllers<Descriptors> | null>(null)\n const [initialValues, setInitialValues] = useState<Fields>(() =>\n fields.reduce((acc, formField) => {\n const tableColumn = table && table.columns.find(field => field.id === formField.tableColumnId)\n const defaultValue = formField ? formField.defaultValue : null\n\n if (tableColumn) {\n acc[tableColumn.name] =\n defaultValue == null ? getTableColumnDefaultValue(tableColumn) : defaultValue\n }\n\n return acc\n }, {} as Fields),\n )\n const controller = propControllers?.fields\n const { container, items } = useTableFormFieldRefs(controller, { fieldsCount: fields.length })\n const [isDone, setIsDone] = useState(false)\n const linkRef = useRef<HTMLAnchorElement>(null)\n\n useImperativeHandle(\n ref,\n () => ({\n getDomNode() {\n return refEl instanceof Element ? refEl : null\n },\n getBoxModel() {\n return refEl instanceof Element ? getBox(refEl) : null\n },\n setPropControllers,\n }),\n [refEl, setPropControllers],\n )\n\n useEffect(() => {\n container(refEl)\n }, [container, refEl])\n\n useEffect(() => {\n if (!isDone) return\n\n let timeoutId = setTimeout(() => setIsDone(false), 2500)\n\n return () => clearTimeout(timeoutId)\n }, [isDone])\n\n function getTableColumn({ tableColumnId }: any) {\n return table && table.columns.find(field => tableColumnId === field.id)\n }\n\n async function handleSubmit(values: any, { setSubmitting, resetForm, setStatus }: any) {\n if (table) {\n const columns: Column[] = []\n\n fields.forEach(field => {\n const tableColumn = getTableColumn(field)\n\n if (tableColumn) {\n const data = values[tableColumn.name]\n\n if (data) {\n columns.push({ columnId: field.tableColumnId, data })\n\n if (field.autofill) {\n localStorage.setItem(\n `${LOCAL_STORAGE_NAMESPACE}/${tableColumn.name}`,\n JSON.stringify(data),\n )\n }\n }\n }\n })\n\n try {\n await client.createTableRecord(table.id, columns)\n setIsDone(true)\n setInitialValues(prev =>\n fields.reduce(\n (acc, field) => {\n const tableColumn = getTableColumn(field)\n\n if (tableColumn) {\n const data = values[tableColumn.name]\n\n if (data && field.autofill) return { ...acc, [tableColumn.name]: data }\n }\n\n return acc\n },\n { ...prev },\n ),\n )\n resetForm()\n\n if (linkRef.current != null) linkRef.current.click()\n } catch (error) {\n setStatus({ error: 'An unexpected error has occurred, please try again later' })\n } finally {\n setSubmitting(false)\n }\n }\n }\n\n useEffect(() => {\n setInitialValues(prev =>\n fields.reduce(\n (acc, formField) => {\n const tableColumn =\n table && table.columns.find(field => field.id === formField.tableColumnId)\n\n if (tableColumn && formField.autofill) {\n const storedValue = localStorage.getItem(\n `${LOCAL_STORAGE_NAMESPACE}/${tableColumn.name}`,\n )\n\n if (storedValue) {\n try {\n acc[tableColumn.name] = JSON.parse(storedValue)\n } catch (e) {\n // Ignore\n }\n }\n }\n\n return acc\n },\n { ...prev },\n ),\n )\n }, [fields, table])\n\n return (\n <FormContextProvider\n value={{ shape, size, contrast, brandColor, labelTextStyle, labelTextColor }}\n >\n {tableId == null ? (\n <Placeholder ref={setRefEl} width={width} margin={margin} />\n ) : (\n <>\n <Formik\n onSubmit={handleSubmit}\n initialValues={initialValues}\n initialStatus={{ error: null }}\n enableReinitialize\n >\n {formik => {\n const error = formik.status && formik.status.error\n const errors = fields\n .map(field => {\n const tableColumn = getTableColumn(field)\n\n return (\n tableColumn &&\n getIn(formik.touched, tableColumn.name) &&\n getIn(formik.errors, tableColumn.name)\n )\n })\n .filter(message => typeof message === 'string')\n\n return (\n <>\n <GridForm\n ref={setRefEl}\n id={id}\n className={cx(width, margin)}\n size={size}\n onSubmit={formik.handleSubmit}\n onReset={formik.handleReset}\n noValidate\n >\n {fields.map((field, index) => {\n const tableColumn = getTableColumn(field)\n\n return (\n <GridItem\n key={field.id}\n ref={items[index]}\n grid={grid}\n index={index}\n rowGap={gap}\n columnGap={gap}\n >\n <Field tableColumn={tableColumn} tableFormField={field} />\n </GridItem>\n )\n })}\n <GridItem\n ref={items[fields.length]}\n grid={grid}\n index={fields.length}\n rowGap={gap}\n columnGap={gap}\n >\n <StyledButton\n type=\"submit\"\n // @ts-ignore: `disabled` is in `'button'` but not in `T`.\n disabled={formik.isSubmitting || isDone}\n shape={shape}\n size={size}\n color={brandColor}\n variant={submitVariant}\n textColor={submitTextColor}\n width={submitWidth}\n alignment={submitAlignment}\n textStyle={submitTextStyle}\n >\n {formik.isSubmitting ? (\n <Spinner />\n ) : isDone ? (\n <IconContainer>\n <Check12 />\n </IconContainer>\n ) : (\n submitLabel\n )}\n </StyledButton>\n {(errors.length > 0 || error) && (\n <ErrorContainer>\n {errors.map(message => (\n <ErrorMessage key={message}>{message}</ErrorMessage>\n ))}\n {error != null && <ErrorMessage>{error}</ErrorMessage>}\n </ErrorContainer>\n )}\n </GridItem>\n </GridForm>\n {submitLink != null && <Link ref={linkRef} hidden link={submitLink} />}\n </>\n )\n }}\n </Formik>\n </>\n )}\n </FormContextProvider>\n )\n})\n\nexport default Form\n"],"mappings":";AA6GI,SA2UY,UA3UZ,KAoYoB,YApYpB;AA3GJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,OAEK;AACP,SAAS,QAAQ,aAAa;AAE9B,SAAS,eAAe;AAExB,SAAS,iBAAiB,0BAA0B;AAEpD;AAAA,EAEE;AAAA,EACA,YAAY;AAAA,E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;AAAA;AAAA,4BAAC;AAAA;AAAA,8BACC,MAAK;AAAA,8BAEL,UAAU,OAAO,gBAAgB;AAAA,8BACjC;AAAA,8BACA;AAAA,8BACA,OAAO;AAAA,8BACP,SAAS;AAAA,8BACT,WAAW;AAAA,8BACX,OAAO;AAAA,8BACP,WAAW;AAAA,8BACX,WAAW;AAAA,8BAEV,iBAAO,eACN,oBAAC,WAAQ,IACP,SACF,oBAAC,iBACC,8BAAC,WAAQ,GACX,IAEA;AAAA;AAAA,0BAEJ;AAAA,2BACE,OAAO,SAAS,KAAK,UACrB,qBAAC,kBACE;AAAA,mCAAO,IAAI,aACV,oBAAC,gBAA4B,qBAAV,OAAkB,CACtC;AAAA,4BACA,SAAS,QAAQ,oBAAC,gBAAc,iBAAM;AAAA,6BACzC;AAAA;AAAA;AAAA,oBAEJ;AAAA;AAAA;AAAA,cACF;AAAA,cACC,cAAc,QAAQ,oBAAC,QAAK,KAAK,SAAS,QAAM,MAAC,MAAM,YAAY;AAAA,eACtE;AAAA,UAEJ;AAAA;AAAA,MACF,GACF;AAAA;AAAA,EAEJ;AAEJ,CAAC;AAED,IAAO,eAAQ;","names":["size","GridItem","alignment","Form"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/components/builtin/Form/Form.tsx"],"sourcesContent":["'use client'\n\nimport {\n useState,\n useEffect,\n useRef,\n useMemo,\n forwardRef,\n ComponentPropsWithoutRef,\n Ref,\n useImperativeHandle,\n ForwardedRef,\n} from 'react'\nimport { Formik, getIn } from 'formik'\n\nimport { Check12 } from '../../icons/Check12'\n\nimport { getSizeHeight as getInputSizeHeight } from './components/Field/components/Input'\n\nimport {\n Size,\n Sizes,\n Provider as FormContextProvider,\n Shape,\n Contrast,\n Alignment,\n Alignments,\n} from './context/FormContext'\nimport Placeholder from './components/Placeholder'\nimport Field from './components/Field'\nimport Spinner from './components/Spinner'\nimport Button from '../Button'\nimport type { TableColumn } from './types'\nimport { Link } from '../../shared/Link'\nimport { getBox, type BoxModelHandle } from '../../../state/modules/read-write/box-models'\nimport { PropControllersHandle } from '../../../state/modules/prop-controller-handles'\nimport { DescriptorsPropControllers } from '../../../prop-controllers/instances'\nimport { useTableFormFieldRefs } from '../../hooks/useTableFormFieldRefs'\nimport { cx } from '@emotion/css'\nimport { useResponsiveGridItem, useResponsiveStyle } from '../../utils/responsive-style'\nimport { type ResponsiveColor } from '../../utils/types'\n\nimport { useMakeswiftGraphQLApiClient } from '../../../runtimes/react/hooks/use-graphql-api-client'\nimport { useStyle } from '../../../runtimes/react/use-style'\nimport { useTable } from '../../../runtimes/react/hooks/makeswift-api'\nimport {\n type LinkData,\n type ResponsiveGapData,\n type ResponsiveLengthData,\n type ResponsiveIconRadioGroupValue,\n type ResponsiveTextStyleData,\n type ResponsiveSelectValue,\n type ResponsiveValue,\n type TableFormFieldsData,\n type TableFormFieldsDescriptor,\n} from '@makeswift/prop-controllers'\n\nconst LOCAL_STORAGE_NAMESPACE = '@@makeswift/components/form'\n\nfunction getSizeFontSize(size: Size): number {\n switch (size) {\n case Sizes.SMALL:\n return 12\n\n case Sizes.MEDIUM:\n return 14\n\n case Sizes.LARGE:\n return 18\n\n default:\n throw new Error(`Invalid form size \"${size}\"`)\n }\n}\n\ntype Props = {\n id?: string\n tableId?: string\n fields?: TableFormFieldsData\n submitLink?: LinkData\n gap?: ResponsiveGapData\n shape?: ResponsiveIconRadioGroupValue<Shape>\n size?: ResponsiveIconRadioGroupValue<Size>\n contrast?: ResponsiveIconRadioGroupValue<Contrast>\n labelTextStyle?: ResponsiveTextStyleData\n labelTextColor?: ResponsiveColor | null\n submitTextStyle?: ResponsiveTextStyleData\n brandColor?: ResponsiveColor | null\n submitTextColor?: ResponsiveColor | null\n submitLabel?: string\n submitVariant?: ResponsiveSelectValue<\n 'flat' | 'outline' | 'shadow' | 'clear' | 'blocky' | 'bubbly' | 'skewed'\n >\n submitWidth?: ResponsiveLengthData\n submitAlignment?: ResponsiveIconRadioGroupValue<Alignment>\n width?: string\n margin?: string\n}\n\ntype GridFormBaseProps = { size?: Props['size'] }\n\ntype GridFormProps = GridFormBaseProps &\n Omit<ComponentPropsWithoutRef<'form'>, keyof GridFormBaseProps>\n\nconst GridForm = forwardRef(function GridFrom(\n { className, size, ...restOfProps }: GridFormProps,\n ref: ForwardedRef<HTMLFormElement>,\n) {\n return (\n <form\n {...restOfProps}\n ref={ref}\n className={cx(\n useStyle({ display: 'flex', flexWrap: 'wrap', width: '100%' }),\n useStyle(\n useResponsiveStyle([size] as const, ([size = Sizes.MEDIUM]) => ({\n fontSize: getSizeFontSize(size),\n })),\n ),\n className,\n )}\n />\n )\n})\n\ntype GridItemBaseProps = {\n grid: ResponsiveValue<{ spans: number[][]; count: number }>\n index: number\n rowGap: Props['gap']\n columnGap: Props['gap']\n}\n\ntype GridItemProps = GridItemBaseProps &\n Omit<ComponentPropsWithoutRef<'div'>, keyof GridItemBaseProps>\n\nconst GridItem = forwardRef(function GridItem(\n { className, grid, index, rowGap, columnGap, ...restOfProps }: GridItemProps,\n ref: ForwardedRef<HTMLDivElement>,\n) {\n return (\n <div\n {...restOfProps}\n ref={ref}\n className={cx(\n useStyle({ alignSelf: 'flex-end', flexDirection: 'column' }),\n useStyle(useResponsiveGridItem({ grid, index, rowGap, columnGap })),\n className,\n )}\n />\n )\n})\n\nfunction getAlignmentMargin(alignment: Alignment): string {\n switch (alignment) {\n case Alignments.LEFT:\n return '0 auto 0 0'\n case Alignments.RIGHT:\n return '0 0 0 auto'\n default:\n return '0 auto'\n }\n}\n\ntype StyledButtonBaseProps = { size?: Props['size']; alignment?: Props['submitAlignment'] }\n\ntype StyledButtonProps = StyledButtonBaseProps &\n Omit<ComponentPropsWithoutRef<typeof Button>, keyof StyledButtonBaseProps>\n\nfunction StyledButton({ className, size, alignment, ...restOfProps }: StyledButtonProps) {\n return (\n <Button\n {...restOfProps}\n as=\"button\"\n className={cx(\n useStyle({ display: 'flex', alignItems: 'center', justifyContent: 'center' }),\n useStyle(\n useResponsiveStyle(\n [size, alignment] as const,\n ([size = Sizes.MEDIUM, alignment = Alignments.CENTER]) => ({\n minHeight: getInputSizeHeight(size),\n maxHeight: getInputSizeHeight(size),\n margin: getAlignmentMargin(alignment),\n paddingTop: 0,\n paddingBottom: 0,\n }),\n ),\n ),\n className,\n )}\n />\n )\n}\n\nfunction ErrorContainer({ className, ...restOfProps }: ComponentPropsWithoutRef<'div'>) {\n return (\n <div\n {...restOfProps}\n className={cx(\n useStyle({\n padding: '8px 16px',\n backgroundColor: '#f19eb9',\n borderRadius: 4,\n marginTop: 16,\n }),\n className,\n )}\n />\n )\n}\n\nfunction IconContainer({ className, ...restOfProps }: ComponentPropsWithoutRef<'div'>) {\n return <div {...restOfProps} className={cx(useStyle({ fill: 'currentColor' }), className)} />\n}\n\nfunction ErrorMessage({ className, ...restOfProps }: ComponentPropsWithoutRef<'p'>) {\n return (\n <p\n {...restOfProps}\n className={cx(\n useStyle({ fontSize: 12, margin: '8px 0', color: 'rgba(127, 0, 0, 0.95)' }),\n className,\n )}\n />\n )\n}\n\nfunction getTableColumnDefaultValue(tableColumn: TableColumn) {\n switch (tableColumn.__typename) {\n case 'CheckboxTableColumn':\n return false\n\n case 'MultipleSelectTableColumn':\n return []\n\n case 'SingleLineTextTableColumn':\n case 'LongTextTableColumn':\n case 'SingleSelectTableColumn':\n case 'PhoneNumberTableColumn':\n case 'EmailTableColumn':\n case 'URLTableColumn':\n case 'NumberTableColumn':\n default:\n return ''\n }\n}\n\ntype Column = { columnId: string; data: Record<string, any> }\ntype Fields = Record<string, string | string[] | boolean>\n\ntype Descriptors = { fields?: TableFormFieldsDescriptor }\n\nconst Form = forwardRef(function Form(\n {\n id,\n tableId,\n fields: fieldsProp,\n submitLabel = 'Submit',\n submitLink,\n shape,\n size,\n contrast,\n brandColor,\n gap,\n width,\n margin,\n submitTextStyle,\n submitVariant,\n submitTextColor,\n submitWidth,\n submitAlignment,\n labelTextStyle,\n labelTextColor,\n }: Props,\n ref: Ref<BoxModelHandle & PropControllersHandle<Descriptors>>,\n) {\n const fields = useMemo(() => fieldsProp?.fields ?? [], [fieldsProp])\n const grid = useMemo(() => fieldsProp?.grid ?? [], [fieldsProp])\n const table = useTable(tableId ?? null)\n const client = useMakeswiftGraphQLApiClient()\n const [refEl, setRefEl] = useState<HTMLElement | null>(null)\n const [propControllers, setPropControllers] =\n useState<DescriptorsPropControllers<Descriptors> | null>(null)\n const [initialValues, setInitialValues] = useState<Fields>(() =>\n fields.reduce((acc, formField) => {\n const tableColumn = table && table.columns.find(field => field.id === formField.tableColumnId)\n const defaultValue = formField ? formField.defaultValue : null\n\n if (tableColumn) {\n acc[tableColumn.name] =\n defaultValue == null ? getTableColumnDefaultValue(tableColumn) : defaultValue\n }\n\n return acc\n }, {} as Fields),\n )\n const controller = propControllers?.fields\n const { container, items } = useTableFormFieldRefs(controller, { fieldsCount: fields.length })\n const [isDone, setIsDone] = useState(false)\n const linkRef = useRef<HTMLAnchorElement>(null)\n\n useImperativeHandle(\n ref,\n () => ({\n getDomNode() {\n return refEl instanceof Element ? refEl : null\n },\n getBoxModel() {\n return refEl instanceof Element ? getBox(refEl) : null\n },\n setPropControllers,\n }),\n [refEl, setPropControllers],\n )\n\n useEffect(() => {\n container(refEl)\n }, [container, refEl])\n\n useEffect(() => {\n if (!isDone) return\n\n let timeoutId = setTimeout(() => setIsDone(false), 2500)\n\n return () => clearTimeout(timeoutId)\n }, [isDone])\n\n function getTableColumn({ tableColumnId }: any) {\n return table && table.columns.find(field => tableColumnId === field.id)\n }\n\n async function handleSubmit(values: any, { setSubmitting, resetForm, setStatus }: any) {\n if (table) {\n const columns: Column[] = []\n\n fields.forEach(field => {\n const tableColumn = getTableColumn(field)\n\n if (tableColumn) {\n const data = values[tableColumn.name]\n\n if (data) {\n columns.push({ columnId: field.tableColumnId, data })\n\n if (field.autofill) {\n localStorage.setItem(\n `${LOCAL_STORAGE_NAMESPACE}/${tableColumn.name}`,\n JSON.stringify(data),\n )\n }\n }\n }\n })\n\n try {\n await client.createTableRecord(table.id, columns)\n setIsDone(true)\n setInitialValues(prev =>\n fields.reduce(\n (acc, field) => {\n const tableColumn = getTableColumn(field)\n\n if (tableColumn) {\n const data = values[tableColumn.name]\n\n if (data && field.autofill) return { ...acc, [tableColumn.name]: data }\n }\n\n return acc\n },\n { ...prev },\n ),\n )\n resetForm()\n\n if (linkRef.current != null) linkRef.current.click()\n } catch (error) {\n setStatus({ error: 'An unexpected error has occurred, please try again later' })\n } finally {\n setSubmitting(false)\n }\n }\n }\n\n useEffect(() => {\n setInitialValues(prev =>\n fields.reduce(\n (acc, formField) => {\n const tableColumn =\n table && table.columns.find(field => field.id === formField.tableColumnId)\n\n if (tableColumn && formField.autofill) {\n const storedValue = localStorage.getItem(\n `${LOCAL_STORAGE_NAMESPACE}/${tableColumn.name}`,\n )\n\n if (storedValue) {\n try {\n acc[tableColumn.name] = JSON.parse(storedValue)\n } catch (e) {\n // Ignore\n }\n }\n }\n\n return acc\n },\n { ...prev },\n ),\n )\n }, [fields, table])\n\n return (\n <FormContextProvider\n value={{ shape, size, contrast, brandColor, labelTextStyle, labelTextColor }}\n >\n {tableId == null ? (\n <Placeholder ref={setRefEl} width={width} margin={margin} />\n ) : (\n <>\n <Formik\n onSubmit={handleSubmit}\n initialValues={initialValues}\n initialStatus={{ error: null }}\n enableReinitialize\n >\n {formik => {\n const error = formik.status && formik.status.error\n const errors = fields\n .map(field => {\n const tableColumn = getTableColumn(field)\n\n return (\n tableColumn &&\n getIn(formik.touched, tableColumn.name) &&\n getIn(formik.errors, tableColumn.name)\n )\n })\n .filter(message => typeof message === 'string')\n\n return (\n <>\n <GridForm\n ref={setRefEl}\n id={id}\n className={cx(width, margin)}\n size={size}\n onSubmit={formik.handleSubmit}\n onReset={formik.handleReset}\n noValidate\n >\n {fields.map((field, index) => {\n const tableColumn = getTableColumn(field)\n\n return (\n <GridItem\n key={field.id}\n ref={items[index]}\n grid={grid}\n index={index}\n rowGap={gap}\n columnGap={gap}\n >\n <Field tableColumn={tableColumn} tableFormField={field} />\n </GridItem>\n )\n })}\n <GridItem\n ref={items[fields.length]}\n grid={grid}\n index={fields.length}\n rowGap={gap}\n columnGap={gap}\n >\n <StyledButton\n type=\"submit\"\n // @ts-ignore: `disabled` is in `'button'` but not in `T`.\n disabled={formik.isSubmitting || isDone}\n shape={shape}\n size={size}\n color={brandColor}\n variant={submitVariant}\n textColor={submitTextColor}\n width={submitWidth}\n alignment={submitAlignment}\n textStyle={submitTextStyle}\n >\n {formik.isSubmitting ? (\n <Spinner />\n ) : isDone ? (\n <IconContainer>\n <Check12 />\n </IconContainer>\n ) : (\n submitLabel\n )}\n </StyledButton>\n {(errors.length > 0 || error) && (\n <ErrorContainer>\n {errors.map(message => (\n <ErrorMessage key={message}>{message}</ErrorMessage>\n ))}\n {error != null && <ErrorMessage>{error}</ErrorMessage>}\n </ErrorContainer>\n )}\n </GridItem>\n </GridForm>\n {submitLink != null && <Link ref={linkRef} hidden link={submitLink} />}\n </>\n )\n }}\n </Formik>\n </>\n )}\n </FormContextProvider>\n )\n})\n\nexport default Form\n"],"mappings":";AA6GI,SA2UY,UA3UZ,KAoYoB,YApYpB;AA3GJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,OAEK;AACP,SAAS,QAAQ,aAAa;AAE9B,SAAS,eAAe;AAExB,SAAS,iBAAiB,0BAA0B;AAEpD;AAAA,EAEE;AAAA,EACA,YAAY;AAAA,EAIZ;AAAA,OACK;AACP,OAAO,iBAAiB;AACxB,OAAO,WAAW;AAClB,OAAO,aAAa;AACpB,OAAO,YAAY;AAEnB,SAAS,YAAY;AACrB,SAAS,cAAmC;AAG5C,SAAS,6BAA6B;AACtC,SAAS,UAAU;AACnB,SAAS,uBAAuB,0BAA0B;AAG1D,SAAS,oCAAoC;AAC7C,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AAazB,MAAM,0BAA0B;AAEhC,SAAS,gBAAgB,MAAoB;AAC3C,UAAQ,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A,2BACE,OAAO,SAAS,KAAK,UACrB,qBAAC,kBACE;AAAA,mCAAO,IAAI,aACV,oBAAC,gBAA4B,qBAAV,OAAkB,CACtC;AAAA,4BACA,SAAS,QAAQ,oBAAC,gBAAc,iBAAM;AAAA,6BACzC;AAAA;AAAA;AAAA,oBAEJ;AAAA;AAAA;AAAA,cACF;AAAA,cACC,cAAc,QAAQ,oBAAC,QAAK,KAAK,SAAS,QAAM,MAAC,MAAM,YAAY;AAAA,eACtE;AAAA,UAEJ;AAAA;AAAA,MACF,GACF;AAAA;AAAA,EAEJ;AAEJ,CAAC;AAED,IAAO,eAAQ;","names":["size","GridItem","alignment","Form"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
3
|
import { useMemo, useSyncExternalStore } from "react";
|
|
4
4
|
import { useIsInBuilder } from "../hooks/use-is-in-builder";
|
|
5
|
-
import {
|
|
5
|
+
import { useApiResourcesClient } from "../hooks/use-api-resources-client";
|
|
6
6
|
import {
|
|
7
7
|
getGoogleFontsParamFromFonts,
|
|
8
8
|
getGoogleFontsParamFromSite,
|
|
@@ -25,7 +25,7 @@ function GoogleFontLink({ fonts, siteId }) {
|
|
|
25
25
|
return /* @__PURE__ */ jsx(PageLink, { precedence: "medium", rel: "stylesheet", href: url });
|
|
26
26
|
}
|
|
27
27
|
function useCachedSite(siteId) {
|
|
28
|
-
const client =
|
|
28
|
+
const client = useApiResourcesClient();
|
|
29
29
|
const getSnapshot = () => siteId == null ? null : client.readSite(siteId);
|
|
30
30
|
return useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot);
|
|
31
31
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/runtimes/react/components/GoogleFontLink.tsx"],"sourcesContent":["'use client'\n\nimport { useMemo, useSyncExternalStore } from 'react'\n\nimport { type Font } from '../../../client'\nimport { type Site } from '../../../api'\nimport { useIsInBuilder } from '../hooks/use-is-in-builder'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/runtimes/react/components/GoogleFontLink.tsx"],"sourcesContent":["'use client'\n\nimport { useMemo, useSyncExternalStore } from 'react'\n\nimport { type Font } from '../../../client'\nimport { type Site } from '../../../api'\nimport { useIsInBuilder } from '../hooks/use-is-in-builder'\nimport { useApiResourcesClient } from '../hooks/use-api-resources-client'\n\nimport {\n getGoogleFontsParamFromFonts,\n getGoogleFontsParamFromSite,\n getGoogleFontsUrl,\n} from '../utils/google-fonts-url'\nimport { PageLink } from './page/head-tags'\n\ntype Props = {\n fonts: Font[]\n siteId: string | null\n}\n\n/**\n * This is experimental, and some of the logic here is duplicated in the `PageHead` component.\n *\n * For now we want to avoid putting this on the critical path for rendering Makeswift pages, so we haven't\n * deduplicated the two.\n */\nexport function GoogleFontLink({ fonts, siteId }: Props) {\n const isInBuilder = useIsInBuilder()\n\n const site = useCachedSite(isInBuilder ? siteId : null)\n\n const fontFamilyParamValue = useMemo(() => {\n if (isInBuilder && site != null) {\n return getGoogleFontsParamFromSite(site)\n }\n return getGoogleFontsParamFromFonts(fonts)\n }, [isInBuilder, site, fonts])\n\n const url = getGoogleFontsUrl(fontFamilyParamValue)\n if (url === '') {\n return null\n }\n\n return <PageLink precedence=\"medium\" rel=\"stylesheet\" href={url} />\n}\n\nfunction useCachedSite(siteId: string | null): Site | null {\n const client = useApiResourcesClient()\n const getSnapshot = () => (siteId == null ? null : client.readSite(siteId))\n\n return useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot)\n}\n"],"mappings":";AA4CS;AA1CT,SAAS,SAAS,4BAA4B;AAI9C,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AAEtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AAalB,SAAS,eAAe,EAAE,OAAO,OAAO,GAAU;AACvD,QAAM,cAAc,eAAe;AAEnC,QAAM,OAAO,cAAc,cAAc,SAAS,IAAI;AAEtD,QAAM,uBAAuB,QAAQ,MAAM;AACzC,QAAI,eAAe,QAAQ,MAAM;AAC/B,aAAO,4BAA4B,IAAI;AAAA,IACzC;AACA,WAAO,6BAA6B,KAAK;AAAA,EAC3C,GAAG,CAAC,aAAa,MAAM,KAAK,CAAC;AAE7B,QAAM,MAAM,kBAAkB,oBAAoB;AAClD,MAAI,QAAQ,IAAI;AACd,WAAO;AAAA,EACT;AAEA,SAAO,oBAAC,YAAS,YAAW,UAAS,KAAI,cAAa,MAAM,KAAK;AACnE;AAEA,SAAS,cAAc,QAAoC;AACzD,QAAM,SAAS,sBAAsB;AACrC,QAAM,cAAc,MAAO,UAAU,OAAO,OAAO,OAAO,SAAS,MAAM;AAEzE,SAAO,qBAAqB,OAAO,WAAW,aAAa,WAAW;AACxE;","names":[]}
|
|
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
|
2
2
|
import { SnippetLocation } from "../../../../client";
|
|
3
3
|
import deepEqual from "../../../../utils/deepEqual";
|
|
4
4
|
import { useIsInBuilder } from "../../hooks/use-is-in-builder";
|
|
5
|
-
import {
|
|
5
|
+
import { useApiResourcesClient } from "../../hooks/use-api-resources-client";
|
|
6
6
|
const filterUsedSnippetProperties = ({
|
|
7
7
|
code,
|
|
8
8
|
builderEnabled,
|
|
@@ -44,7 +44,7 @@ function usePageSnippets({ page }) {
|
|
|
44
44
|
return { headSnippets, bodySnippets };
|
|
45
45
|
}
|
|
46
46
|
function useCachedPage(pageId) {
|
|
47
|
-
const client =
|
|
47
|
+
const client = useApiResourcesClient();
|
|
48
48
|
const getSnapshot = () => pageId == null ? null : client.readPage(pageId);
|
|
49
49
|
const page = useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot);
|
|
50
50
|
return page;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/runtimes/react/components/hooks/use-page-snippets.ts"],"sourcesContent":["import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'\n\nimport { type MakeswiftPageDocument, type Snippet, SnippetLocation } from '../../../../client'\nimport { type Page as PageType } from '../../../../api'\n\nimport deepEqual from '../../../../utils/deepEqual'\n\nimport { useIsInBuilder } from '../../hooks/use-is-in-builder'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/runtimes/react/components/hooks/use-page-snippets.ts"],"sourcesContent":["import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'\n\nimport { type MakeswiftPageDocument, type Snippet, SnippetLocation } from '../../../../client'\nimport { type Page as PageType } from '../../../../api'\n\nimport deepEqual from '../../../../utils/deepEqual'\n\nimport { useIsInBuilder } from '../../hooks/use-is-in-builder'\nimport { useApiResourcesClient } from '../../hooks/use-api-resources-client'\n\nconst filterUsedSnippetProperties = ({\n code,\n builderEnabled,\n liveEnabled,\n location,\n cleanup,\n}: Snippet) => ({\n code,\n builderEnabled,\n liveEnabled,\n location,\n cleanup,\n})\n\nexport function usePageSnippets({ page }: { page: MakeswiftPageDocument }) {\n const isInBuilder = useIsInBuilder()\n const [snippets, setSnippets] = useState(page.snippets)\n\n // We're using cached results here for page snippets so that anytime the user\n // changes the snippets or fonts on the builder, the change would be reflected\n // here. See this PR for discussions and things we can do to improve it in the\n // future: https://github.com/makeswift/makeswift/pull/77\n const cachedPage = useCachedPage(isInBuilder ? page.id : null)\n useEffect(() => {\n if (cachedPage == null) return\n\n const oldSnippets = snippets.map(filterUsedSnippetProperties)\n const newSnippets = cachedPage.snippets.map(filterUsedSnippetProperties)\n\n if (deepEqual(newSnippets, oldSnippets)) return\n\n setSnippets(cachedPage.snippets)\n }, [cachedPage])\n\n const filteredSnippets = useMemo(\n () => snippets.filter(snippet => (isInBuilder ? snippet.builderEnabled : snippet.liveEnabled)),\n [snippets, isInBuilder],\n )\n\n const headSnippets = useMemo(\n () => filteredSnippets.filter(snippet => snippet.location === SnippetLocation.Head),\n [filteredSnippets],\n )\n\n const bodySnippets = useMemo(\n () => filteredSnippets.filter(snippet => snippet.location === SnippetLocation.Body),\n [filteredSnippets],\n )\n\n return { headSnippets, bodySnippets }\n}\n\nfunction useCachedPage(pageId: string | null): PageType | null {\n const client = useApiResourcesClient()\n const getSnapshot = () => (pageId == null ? null : client.readPage(pageId))\n\n const page = useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot)\n\n return page\n}\n"],"mappings":"AAAA,SAAS,WAAW,SAAS,UAAU,4BAA4B;AAEnE,SAAmD,uBAAuB;AAG1E,OAAO,eAAe;AAEtB,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AAEtC,MAAM,8BAA8B,CAAC;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,OAAgB;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,gBAAgB,EAAE,KAAK,GAAoC;AACzE,QAAM,cAAc,eAAe;AACnC,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,KAAK,QAAQ;AAMtD,QAAM,aAAa,cAAc,cAAc,KAAK,KAAK,IAAI;AAC7D,YAAU,MAAM;AACd,QAAI,cAAc;AAAM;AAExB,UAAM,cAAc,SAAS,IAAI,2BAA2B;AAC5D,UAAM,cAAc,WAAW,SAAS,IAAI,2BAA2B;AAEvE,QAAI,UAAU,aAAa,WAAW;AAAG;AAEzC,gBAAY,WAAW,QAAQ;AAAA,EACjC,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM,mBAAmB;AAAA,IACvB,MAAM,SAAS,OAAO,aAAY,cAAc,QAAQ,iBAAiB,QAAQ,WAAY;AAAA,IAC7F,CAAC,UAAU,WAAW;AAAA,EACxB;AAEA,QAAM,eAAe;AAAA,IACnB,MAAM,iBAAiB,OAAO,aAAW,QAAQ,aAAa,gBAAgB,IAAI;AAAA,IAClF,CAAC,gBAAgB;AAAA,EACnB;AAEA,QAAM,eAAe;AAAA,IACnB,MAAM,iBAAiB,OAAO,aAAW,QAAQ,aAAa,gBAAgB,IAAI;AAAA,IAClF,CAAC,gBAA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