3 Commits

Author SHA1 Message Date
0fb510dbaf update version number to 1.0.2 2025-07-04 19:34:38 +09:00
5803a133c3 support language translation. 2025-07-04 19:29:11 +09:00
137105311e optimize build tool chain. 2025-07-03 20:20:06 +09:00
22 changed files with 958 additions and 932 deletions

View File

@@ -2,6 +2,17 @@
"version": "0.2", "version": "0.2",
"language": "en,en-gb", "language": "en,en-gb",
"ignoreWords": [], "ignoreWords": [],
"words": ["blankspace", "Heiti", "jscoverage", "Kaku", "kintone", "kintoneplugin", "kypes", "Ligh", "moize"], "words": [
"blankspace",
"Heiti",
"jscoverage",
"Kaku",
"kintone",
"kintoneplugin",
"kypes",
"Ligh",
"moize",
"rspack"
],
"ignorePaths": [".env"] "ignorePaths": [".env"]
} }

1081
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +1,29 @@
{ {
"name": "kintone-plugin-filelookup", "name": "kintone-plugin-filelookup",
"version": "1.0.1", "version": "1.0.2",
"scripts": { "scripts": {
"prepare": "node scripts/prepare-private-key.js", "gen": "run-s gen:*",
"gen:key": "node scripts/generate-private-key.js",
"start": "node scripts/npm-start.js", "start": "node scripts/npm-start.js",
"develop": "npm run build -- --watch", "develop": "npm run build -- --watch",
"build": "npm run prepare && cross-env NODE_ENV=development rspack build", "prebuild": "npm run gen",
"build:prod": "npm run prepare && cross-env NODE_ENV=production rspack build", "prebuild:prod": "npm run gen",
"dts-gen": "kintone-dts-gen", "build": "cross-env NODE_ENV=development rspack build",
"build:prod": "cross-env NODE_ENV=production rspack build",
"lint": "eslint src --ext .js,.jsx,.ts,.tsx", "lint": "eslint src --ext .js,.jsx,.ts,.tsx",
"upload": "env-cmd --silent kintone-plugin-uploader dist/plugin.zip --watch --waiting-dialog-ms 3000" "upload": "env-cmd --silent kintone-plugin-uploader dist/plugin.zip --watch --waiting-dialog-ms 3000"
}, },
"dependencies": { "dependencies": {
"@kintone/rest-api-client": "^5.7.4", "@kintone/rest-api-client": "^5.7.4",
"angular-expressions": "^1.4.3",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"dayjs": "^1.11.13", "i18next": "^25.3.0",
"immer": "^10.1.1", "immer": "^10.1.1",
"moize": "^6.1.6", "moize": "^6.1.6",
"nanoid": "^5.1.5", "nanoid": "^5.1.5",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"react-error-boundary": "^6.0.0", "react-error-boundary": "^6.0.0",
"react-i18next": "^15.6.0",
"tiny-invariant": "^1.3.3" "tiny-invariant": "^1.3.3"
}, },
"devDependencies": { "devDependencies": {
@@ -29,21 +31,19 @@
"@kintone/dts-gen": "^8.1.2", "@kintone/dts-gen": "^8.1.2",
"@kintone/plugin-uploader": "^9.1.5", "@kintone/plugin-uploader": "^9.1.5",
"@kintone/webpack-plugin-kintone-plugin": "^8.0.11", "@kintone/webpack-plugin-kintone-plugin": "^8.0.11",
"@rspack/cli": "^1.4.0", "@rspack/cli": "^1.4.3",
"@rspack/core": "^1.4.0", "@rspack/core": "^1.4.3",
"@shin-chan/kypes": "^0.0.7", "@shin-chan/kypes": "^0.0.7",
"@swc/helpers": "^0.5.17",
"@types/react": "^19.1.8", "@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.1.6",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"css-loader": "^7.1.2",
"env-cmd": "^10.1.0", "env-cmd": "^10.1.0",
"eslint": "^9.29.0", "eslint": "^9.30.1",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"globals": "^16.2.0", "globals": "^16.3.0",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"prettier": "^3.6.1", "prettier": "^3.6.2",
"style-loader": "^4.0.0", "ts-node": "^10.9.2",
"typescript": "^5.8.3" "typescript": "^5.8.3"
} }
} }

View File

@@ -1,7 +1,7 @@
{ {
"$schema": "https://raw.githubusercontent.com/kintone/js-sdk/%40kintone/plugin-manifest-validator%4010.2.0/packages/plugin-manifest-validator/manifest-schema.json", "$schema": "https://raw.githubusercontent.com/kintone/js-sdk/%40kintone/plugin-manifest-validator%4010.2.0/packages/plugin-manifest-validator/manifest-schema.json",
"manifest_version": 1, "manifest_version": 1,
"version": "1.0.1", "version": "1.0.2",
"type": "APP", "type": "APP",
"desktop": { "desktop": {
"js": ["js/desktop.js"] "js": ["js/desktop.js"]
@@ -13,6 +13,7 @@
"config": { "config": {
"html": "html/config.html", "html": "html/config.html",
"js": ["js/config.js"], "js": ["js/config.js"],
"css": ["js/config.css"],
"required_params": ["lookup"] "required_params": ["lookup"]
}, },
"name": { "name": {

View File

@@ -1,99 +0,0 @@
/* eslint-env node */
const path = require('path');
const KintonePlugin = require('@kintone/webpack-plugin-kintone-plugin');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? false : 'inline-cheap-module-source-map',
entry: { config: './src/config/index.tsx', desktop: './src/desktop/index.tsx' },
output: {
path: path.resolve(__dirname, 'plugin', 'js'),
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.(j|t)s$/,
exclude: [/[\\/]node_modules[\\/]/],
loader: 'builtin:swc-loader',
options: {
sourceMaps: !isProduction,
jsc: {
parser: {
syntax: 'typescript',
},
transform: {
react: {
runtime: 'automatic',
development: !isProduction,
},
},
externalHelpers: true,
},
env: {
targets: 'Chrome >= 48',
},
},
},
{
test: /\.(j|t)sx$/,
loader: 'builtin:swc-loader',
exclude: [/[\\/]node_modules[\\/]/],
options: {
sourceMaps: !isProduction,
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
runtime: 'automatic',
development: !isProduction,
},
},
externalHelpers: true,
},
env: {
targets: 'Chrome >= 48', // browser compatibility
},
},
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
exclude: /\.module\.css$/,
},
{
test: /\.module\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
sourceMap: !isProduction,
modules: {
localIdentName: isProduction ? '[hash:base64]' : '[name]__[local]--[hash:base64:5]',
namedExport: false,
},
},
},
],
},
],
},
plugins: [
new KintonePlugin({
manifestJSONPath: './plugin/manifest.json',
privateKeyPath: './private.ppk',
pluginZipPath: './dist/plugin.zip',
}),
],
};

70
rspack.config.ts Normal file
View File

@@ -0,0 +1,70 @@
import { defineConfig } from '@rspack/cli';
import { rspack } from '@rspack/core';
import KintonePlugin from '@kintone/webpack-plugin-kintone-plugin';
const isDev = process.env.NODE_ENV === 'development';
// Target browsers, see: https://github.com/browserslist/browserslist
const targets = ['last 2 versions', '> 0.2%', 'not dead', 'Firefox ESR'];
export default defineConfig({
mode: isDev ? 'development' : 'production',
devtool: isDev ? 'inline-cheap-module-source-map' : false,
entry: { config: './src/config/index.tsx', desktop: './src/desktop/index.tsx' },
output: {
path: './plugin/js',
filename: '[name].js',
},
resolve: {
extensions: ['...', '.ts', '.tsx', '.jsx'],
},
module: {
rules: [
{
test: /\.(jsx?|tsx?)$/,
use: [
{
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
},
env: { targets },
},
},
],
},
],
parser: {
'css/auto': {
namedExports: false,
},
},
},
plugins: [
new KintonePlugin({
manifestJSONPath: './plugin/manifest.json',
privateKeyPath: './private.ppk',
pluginZipPath: './dist/plugin.zip',
}),
],
optimization: {
minimizer: [
new rspack.SwcJsMinimizerRspackPlugin(),
new rspack.LightningCssMinimizerRspackPlugin({
minimizerOptions: { targets },
}),
],
},
experiments: {
css: true,
},
performance: {
maxEntrypointSize: 1024000,
maxAssetSize: 1024000,
},
});

View File

@@ -7,14 +7,16 @@
background-color: rgba(0, 0, 0, 0.7); background-color: rgba(0, 0, 0, 0.7);
z-index: 9999; z-index: 9999;
} }
.spinner-container {
.spinnerContainer {
position: fixed; position: fixed;
top: 50%; top: 50%;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
z-index: 10000; z-index: 10000;
} }
.spinner-container .spinner {
.spinnerContainer .spinner {
font-size: 10px; font-size: 10px;
width: 1em; width: 1em;
height: 1em; height: 1em;
@@ -24,6 +26,7 @@
animation: mulShdSpin 1.1s infinite ease; animation: mulShdSpin 1.1s infinite ease;
transform: translateZ(0); transform: translateZ(0);
} }
@keyframes mulShdSpin { @keyframes mulShdSpin {
0%, 0%,
100% { 100% {

View File

@@ -1,5 +1,3 @@
import { PLUGIN_ID } from './global';
export interface PluginConfigLookupItem { export interface PluginConfigLookupItem {
lookupFieldCode: string; lookupFieldCode: string;
srcAttachmentFieldCode: string; srcAttachmentFieldCode: string;
@@ -20,17 +18,18 @@ const decodeConfigLookup = (lookup: string): PluginConfigLookup | null => {
try { try {
return JSON.parse(lookup) as PluginConfigLookup; return JSON.parse(lookup) as PluginConfigLookup;
} catch (e) { } catch (e) {
console.error('Failed to decode config lookup:', e);
return null; return null;
} }
}; };
export const loadPluginConfigLookup = (): PluginConfigLookup | null => { export const loadPluginConfigLookup = (pluginId: string): PluginConfigLookup | null => {
const config = kintone.plugin.app.getConfig(PLUGIN_ID); const config = kintone.plugin.app.getConfig(pluginId);
return decodeConfigLookup(config.lookup); return decodeConfigLookup(config.lookup);
}; };
export const loadPluginConfig = (): PluginConfig | null => { export const loadPluginConfig = (pluginId: string): PluginConfig | null => {
const config = kintone.plugin.app.getConfig(PLUGIN_ID); const config = kintone.plugin.app.getConfig(pluginId);
const lookup = decodeConfigLookup(config.lookup); const lookup = decodeConfigLookup(config.lookup);
return lookup ? { lookup } : null; return lookup ? { lookup } : null;
}; };

View File

@@ -1,9 +1,7 @@
import { KintoneFormFieldProperty, KintoneRestAPIClient } from '@kintone/rest-api-client'; import { KintoneFormFieldProperty, KintoneRestAPIClient } from '@kintone/rest-api-client';
import {
AppID as KintoneAppId,
Properties as KintoneFormFieldProperties,
} from '@kintone/rest-api-client/lib/src/client/types';
import { PluginConfigLookup } from './config'; import { PluginConfigLookup } from './config';
import { naturalCompare } from './stringUtils';
import { KintoneAppId, KintoneFormFieldProperties } from './types';
export interface PluginContext { export interface PluginContext {
appId: KintoneAppId; appId: KintoneAppId;
@@ -12,14 +10,6 @@ export interface PluginContext {
lookupFields: KintoneFormFieldProperty.Lookup[]; lookupFields: KintoneFormFieldProperty.Lookup[];
} }
const naturalCompare = (a: string, b: string): number => {
const locales = new Set<string>([...navigator.languages, 'en-US', 'ja-JP']);
return new Intl.Collator(Array.from(locales), {
sensitivity: 'variant',
numeric: true,
}).compare(a, b);
};
const filterAttachmentFields = (properties: KintoneFormFieldProperties): KintoneFormFieldProperty.File[] => { const filterAttachmentFields = (properties: KintoneFormFieldProperties): KintoneFormFieldProperty.File[] => {
return Object.values(properties) return Object.values(properties)
.filter((property) => property.type === 'FILE') .filter((property) => property.type === 'FILE')
@@ -32,20 +22,20 @@ const filterLookupFields = (properties: KintoneFormFieldProperties): KintoneForm
.sort((a, b) => naturalCompare(`${a.label} (${a.code})`, `${b.label} (${b.code})`)); .sort((a, b) => naturalCompare(`${a.label} (${a.code})`, `${b.label} (${b.code})`));
}; };
const getFormFieldsProperties = async (appId: KintoneAppId): Promise<KintoneFormFieldProperties> => { const getFormFieldsProperties = async (appId: KintoneAppId, preview: boolean): Promise<KintoneFormFieldProperties> => {
const client = new KintoneRestAPIClient(); const client = new KintoneRestAPIClient();
const { properties } = await client.app.getFormFields({ app: appId, lang: 'en', preview: false }); const { properties } = await client.app.getFormFields({ app: appId, preview });
return properties; return properties;
}; };
export const getPluginContext = async (appId: KintoneAppId): Promise<PluginContext> => { export const getPluginContext = async (appId: KintoneAppId, isConfig: boolean): Promise<PluginContext> => {
const context: PluginContext = { const context: PluginContext = {
appId: appId, appId: appId,
formFieldsProperties: {}, formFieldsProperties: {},
attachmentFields: {}, attachmentFields: {},
lookupFields: [], lookupFields: [],
}; };
const properties = await getFormFieldsProperties(appId); const properties = await getFormFieldsProperties(appId, isConfig);
context.formFieldsProperties[appId] = properties; context.formFieldsProperties[appId] = properties;
context.attachmentFields[appId] = filterAttachmentFields(properties); context.attachmentFields[appId] = filterAttachmentFields(properties);
const lookupFields = filterLookupFields(properties); const lookupFields = filterLookupFields(properties);
@@ -54,7 +44,7 @@ export const getPluginContext = async (appId: KintoneAppId): Promise<PluginConte
.filter((value, index, self) => self.indexOf(value) === index); .filter((value, index, self) => self.indexOf(value) === index);
await Promise.all( await Promise.all(
relatedAppIds.map(async (relatedAppId) => { relatedAppIds.map(async (relatedAppId) => {
const relatedProperties = await getFormFieldsProperties(relatedAppId); const relatedProperties = await getFormFieldsProperties(relatedAppId, false);
context.formFieldsProperties[relatedAppId] = relatedProperties; context.formFieldsProperties[relatedAppId] = relatedProperties;
context.attachmentFields[relatedAppId] = filterAttachmentFields(relatedProperties); context.attachmentFields[relatedAppId] = filterAttachmentFields(relatedProperties);
}), }),

View File

@@ -1,12 +0,0 @@
import invariant from 'tiny-invariant';
export const PLUGIN_ID = kintone.$PLUGIN_ID;
invariant(PLUGIN_ID, 'The PLUGIN_ID is not available. Please ensure you are on a Kintone plugin page.');
const KintoneUserLanguages = ['en', 'ja', 'zh', 'zh-TW', 'es', 'pt-BR', 'th'] as const;
export type KintoneUserLanguages = (typeof KintoneUserLanguages)[number];
export const LANGUAGE = kintone.getLoginUser().language as KintoneUserLanguages;
invariant(
KintoneUserLanguages.includes(LANGUAGE),
`Unsupported language: ${LANGUAGE}. Supported languages are: ${KintoneUserLanguages.join(', ')}`,
);

View File

@@ -0,0 +1,10 @@
import { LanguageDetectorModule } from 'i18next';
const KintoneLanguageDetector: LanguageDetectorModule = {
type: 'languageDetector',
// init: () => {},
detect: () => kintone.getLoginUser().language,
// cacheUserLanguage: () => {},
};
export default KintoneLanguageDetector;

View File

@@ -0,0 +1,7 @@
export const naturalCompare = (a: string, b: string): number => {
const locales = new Set<string>([...navigator.languages, 'en-US', 'ja-JP']);
return new Intl.Collator(Array.from(locales), {
sensitivity: 'variant',
numeric: true,
}).compare(a, b);
};

7
src/common/types.ts Normal file
View File

@@ -0,0 +1,7 @@
import { KintoneFormFieldProperty } from '@kintone/rest-api-client';
export type KintoneAppId = string | number;
export type KintoneFormFieldProperties = {
[fieldCode: string]: KintoneFormFieldProperty.OneOf;
};

View File

@@ -5,11 +5,16 @@ import ErrorFallback from '../common/ErrorFallback';
import Loading from '../common/Loading'; import Loading from '../common/Loading';
import Settings from './Settings'; import Settings from './Settings';
const ConfigApp: React.FC = () => { interface ConfigAppProps {
pluginId: string;
}
const ConfigApp: React.FC<ConfigAppProps> = (props) => {
const { pluginId } = props;
return ( return (
<ErrorBoundary FallbackComponent={ErrorFallback}> <ErrorBoundary FallbackComponent={ErrorFallback}>
<React.Suspense fallback={<Loading />}> <React.Suspense fallback={<Loading />}>
<Settings /> <Settings pluginId={pluginId} />
</React.Suspense> </React.Suspense>
</ErrorBoundary> </ErrorBoundary>
); );

View File

@@ -1,6 +1,8 @@
import React from 'react'; import React from 'react';
import { produce } from 'immer'; import { produce } from 'immer';
import moize from 'moize';
import { useTranslation } from 'react-i18next';
import invariant from 'tiny-invariant'; import invariant from 'tiny-invariant';
import { import {
loadPluginConfigLookup, loadPluginConfigLookup,
@@ -21,7 +23,6 @@ import KintonePluginTableTd from '../common/ui/KintonePluginTableTd';
import KintonePluginTableTh from '../common/ui/KintonePluginTableTh'; import KintonePluginTableTh from '../common/ui/KintonePluginTableTh';
import KintonePluginTitle from '../common/ui/KintonePluginTitle'; import KintonePluginTitle from '../common/ui/KintonePluginTitle';
import moize from 'moize';
import styles from './Settings.module.css'; import styles from './Settings.module.css';
const hasDuplicate = <T,>(items: T[], func: (a: T, b: T) => boolean = (a, b) => a === b): boolean => { const hasDuplicate = <T,>(items: T[], func: (a: T, b: T) => boolean = (a, b) => a === b): boolean => {
@@ -145,14 +146,20 @@ const FieldSelectTableRow: React.FC<FieldSelectTableRowProps> = (props) => {
const cachedPluginContext = moize.promise(getPluginContext); const cachedPluginContext = moize.promise(getPluginContext);
const Settings: React.FC = () => { interface SettingsProps {
pluginId: string;
}
const Settings: React.FC<SettingsProps> = (props) => {
const { pluginId } = props;
const { t } = useTranslation();
const appId = kintone.app.getId(); const appId = kintone.app.getId();
invariant(appId, 'The app ID is not available. Please ensure you are on a Kintone app page.'); invariant(appId, 'The app ID is not available. Please ensure you are on a Kintone app page.');
const context = React.use(cachedPluginContext(appId)); const context = React.use(cachedPluginContext(appId, true));
const [mappings, setMappings] = React.useState<PluginConfigLookup>( const [mappings, setMappings] = React.useState<PluginConfigLookup>(
() => () =>
filterConfigByPluginContext(loadPluginConfigLookup(), context) ?? [ filterConfigByPluginContext(loadPluginConfigLookup(pluginId), context) ?? [
{ lookupFieldCode: '', srcAttachmentFieldCode: '', destAttachmentFieldCode: '' }, { lookupFieldCode: '', srcAttachmentFieldCode: '', destAttachmentFieldCode: '' },
], ],
); );
@@ -207,13 +214,13 @@ const Settings: React.FC = () => {
const handleOnSubmit = (e: React.FormEvent<HTMLFormElement>) => { const handleOnSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
if (mappings.find((item) => item.destAttachmentFieldCode === '') != null) { if (mappings.find((item) => item.destAttachmentFieldCode === '') != null) {
setError('Incomplete field mapping found'); setError(t('settings.lookup.errors.incomplete-field-mapping-found'));
} else if (hasDuplicateDestAttachmentFields(mappings)) { } else if (hasDuplicateDestAttachmentFields(mappings)) {
setError('Same destination attachment fields found'); setError(t('settings.lookup.errors.same-destination-attachment-field-found'));
} else { } else {
setError(''); setError('');
savePluginConfigLookup(mappings, () => { savePluginConfigLookup(mappings, () => {
alert('The plug-in settings have been saved. Please update the app!'); alert(t('on-saved'));
window.location.href = `../../flow?app=${appId}`; window.location.href = `../../flow?app=${appId}`;
}); });
} }
@@ -226,7 +233,7 @@ const Settings: React.FC = () => {
return ( return (
<section className="settings"> <section className="settings">
<KintonePluginLabel>Settings for the Kintone Lookup File Sync plugin</KintonePluginLabel> <KintonePluginLabel>{t('title')}</KintonePluginLabel>
{error !== '' && ( {error !== '' && (
<KintonePluginRow> <KintonePluginRow>
<KintonePluginAlert>{error}</KintonePluginAlert> <KintonePluginAlert>{error}</KintonePluginAlert>
@@ -235,29 +242,32 @@ const Settings: React.FC = () => {
<form onSubmit={handleOnSubmit}> <form onSubmit={handleOnSubmit}>
<KintonePluginRow> <KintonePluginRow>
<KintonePluginTitle> <KintonePluginTitle>
Field Mappings<KintonePluginRequire>*</KintonePluginRequire> {t('settings.lookup.title')}
<KintonePluginRequire>*</KintonePluginRequire>
</KintonePluginTitle> </KintonePluginTitle>
<KintonePluginDesc> <KintonePluginDesc>{t('settings.lookup.description')}</KintonePluginDesc>
Select lookup and attachment fields that used for the file synchronization.
</KintonePluginDesc>
{context.lookupFields.length === 0 ? ( {context.lookupFields.length === 0 ? (
<KintonePluginAlert> <KintonePluginAlert>{t('settings.lookup.errors.no-lookup-field-found')}</KintonePluginAlert>
No lookup fields found in the app. Please add a lookup field to use this plugin.
</KintonePluginAlert>
) : ( ) : (
<KintonePluginTable> <KintonePluginTable>
<thead> <thead>
<tr> <tr>
<KintonePluginTableTh variant="title">Lookup Field</KintonePluginTableTh> <KintonePluginTableTh variant="title">
<KintonePluginTableTh variant="title">Source Attachment Field (in Related App)</KintonePluginTableTh> {t('settings.lookup.messages.lookup-field')}
<KintonePluginTableTh variant="title">Destination Attachment Field</KintonePluginTableTh> </KintonePluginTableTh>
<KintonePluginTableTh variant="title">
{t('settings.lookup.messages.source-attachment-field')}
</KintonePluginTableTh>
<KintonePluginTableTh variant="title">
{t('settings.lookup.messages.destination-attachment-field')}
</KintonePluginTableTh>
<KintonePluginTableTh variant="blankspace" /> <KintonePluginTableTh variant="blankspace" />
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{mappings.map((row, idx) => ( {mappings.map((row, idx) => (
<FieldSelectTableRow <FieldSelectTableRow
key={idx} key={`${row.lookupFieldCode}-${row.srcAttachmentFieldCode}-${row.destAttachmentFieldCode}-${idx}`}
context={context} context={context}
row={row} row={row}
onUpdate={(draft) => { onUpdate={(draft) => {
@@ -277,10 +287,10 @@ const Settings: React.FC = () => {
</KintonePluginRow> </KintonePluginRow>
<KintonePluginRow className={styles.buttons}> <KintonePluginRow className={styles.buttons}>
<KintonePluginButton variant="dialog-cancel" type="button" onClick={handleOnClickCancel}> <KintonePluginButton variant="dialog-cancel" type="button" onClick={handleOnClickCancel}>
Cancel {t('buttons.cancel')}
</KintonePluginButton> </KintonePluginButton>
<KintonePluginButton variant="dialog-ok" type="submit"> <KintonePluginButton variant="dialog-ok" type="submit">
Save {t('buttons.save')}
</KintonePluginButton> </KintonePluginButton>
</KintonePluginRow> </KintonePluginRow>
</form> </form>

27
src/config/i18n.ts Normal file
View File

@@ -0,0 +1,27 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import kintoneLanguageDetector from '../common/kintoneLanguageDetector';
import enTranslation from './locales/en.json';
import jaTranslation from './locales/ja.json';
i18n
.use(kintoneLanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
// debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
resources: {
en: {
translation: enTranslation,
},
ja: {
translation: jaTranslation,
},
},
});
export default i18n;

View File

@@ -6,11 +6,15 @@ import ConfigApp from './ConfigApp';
import '../common/ui/51-modern-default.css'; import '../common/ui/51-modern-default.css';
const root = document.getElementById('plugin-config-root'); import './i18n';
invariant(root, 'The plugin configuration root element "plugin-config-root" is not found.');
ReactDOM.createRoot(root).render( ((PLUGIN_ID) => {
<React.StrictMode> const root = document.getElementById('plugin-config-root');
<ConfigApp /> invariant(root, 'The plugin configuration root element "plugin-config-root" is not found.');
</React.StrictMode>,
); ReactDOM.createRoot(root).render(
<React.StrictMode>
<ConfigApp pluginId={PLUGIN_ID} />
</React.StrictMode>,
);
})(kintone.$PLUGIN_ID);

View File

@@ -0,0 +1,24 @@
{
"title": "Settings for the Kintone Lookup File Sync plugin",
"settings": {
"lookup": {
"title": "Field Mappings",
"description": "Select lookup and attachment fields that used for the file synchronization.",
"messages": {
"lookup-field": "Lookup Field",
"source-attachment-field": "Source Attachment Field (in Related App)",
"destination-attachment-field": "Destination Attachment Field"
},
"errors": {
"no-lookup-field-found": "No lookup fields found in the app. Please add a lookup field to use this plugin.",
"incomplete-field-mapping-found": "Incomplete field mapping found",
"same-destination-attachment-field-found": "Same destination attachment fields found"
}
}
},
"buttons": {
"save": "Save",
"cancel": "Cancel"
},
"on-saved": "The plug-in settings have been saved. Please update the app!"
}

View File

@@ -0,0 +1,24 @@
{
"title": "Lookupファイル同期プラグイン設定",
"settings": {
"lookup": {
"title": "フィールドマッピング",
"description": "ルックアップフィールドでファイルを同期させる添付ファイルフィールドの対応付けを行います。",
"messages": {
"lookup-field": "ルックアップフィールド",
"source-attachment-field": "同期元の添付ファイルフィールド (関連アプリ)",
"destination-attachment-field": "同期先の添付ファイルフィールド"
},
"errors": {
"no-lookup-field-found": "同期可能なルックアップフィールドが見つかりません。フォームの設定を見直してください。",
"incomplete-field-mapping-found": "設定の完了していないマッピングが見つかりました。",
"same-destination-attachment-field-found": "同期先の添付ファイルフィールドが重複しています。"
}
}
},
"buttons": {
"save": "保存",
"cancel": "キャンセル"
},
"on-saved": "設定を保存しました。アプリを更新してください。"
}

View File

@@ -8,142 +8,145 @@ interface UpdateRecordAttachmentFieldValueItem {
} }
type UpdateRecordAttachmentFieldValue = UpdateRecordAttachmentFieldValueItem[]; type UpdateRecordAttachmentFieldValue = UpdateRecordAttachmentFieldValueItem[];
kintone.events.on( ((PLUGIN_ID) => {
['app.record.create.show', 'app.record.edit.show', 'mobile.app.record.create.show', 'mobile.app.record.edit.show'], kintone.events.on(
function ( ['app.record.create.show', 'app.record.edit.show', 'mobile.app.record.create.show', 'mobile.app.record.edit.show'],
event: function (
| kintone.events.AppRecordCreateShowEvent event:
| kintone.events.AppRecordEditShowEvent | kintone.events.AppRecordCreateShowEvent
| kintone.events.MobileAppRecordCreateShowEvent | kintone.events.AppRecordEditShowEvent
| kintone.events.MobileAppRecordEditShowEvent, | kintone.events.MobileAppRecordCreateShowEvent
) { | kintone.events.MobileAppRecordEditShowEvent,
const mappings = loadPluginConfigLookup(); ) {
mappings?.forEach((mapping) => { const mappings = loadPluginConfigLookup(PLUGIN_ID);
if (mapping.destAttachmentFieldCode in event.record) { mappings?.forEach((mapping) => {
(event.record[mapping.destAttachmentFieldCode] as any).disabled = true; if (mapping.destAttachmentFieldCode in event.record) {
} (event.record[mapping.destAttachmentFieldCode] as any).disabled = true;
}); }
return event; });
},
);
kintone.events.on(
[
'app.record.create.submit.success',
'app.record.edit.submit.success',
'mobile.app.record.create.submit.success',
'mobile.app.record.edit.submit.success',
],
async (
event:
| kintone.events.AppRecordCreateSubmitSuccessEvent
| kintone.events.AppRecordEditSubmitSuccessEvent
| kintone.events.MobileAppRecordCreateSubmitSuccessEvent
| kintone.events.MobileAppRecordEditSubmitSuccessEvent,
) => {
const context = await getPluginContext(event.appId);
const mappings = filterConfigByPluginContext(loadPluginConfigLookup(), context);
if (mappings == null) {
return event; return event;
} },
const client = new KintoneRestAPIClient(); );
await Promise.all<void>(
mappings.map(async (mapping) => { kintone.events.on(
const lookupField = event.record[mapping.lookupFieldCode]; [
invariant( 'app.record.create.submit.success',
lookupField?.type === 'NUMBER' || lookupField?.type === 'SINGLE_LINE_TEXT', 'app.record.edit.submit.success',
'The field type of lookup field code must be number or single line text field.', 'mobile.app.record.create.submit.success',
); 'mobile.app.record.edit.submit.success',
const lookupFieldProperty = context.lookupFields.find((p) => p.code === mapping.lookupFieldCode); ],
invariant(lookupFieldProperty != null, 'The property of lookup field not found.'); async (
const destAttachmentField = event.record[mapping.destAttachmentFieldCode]; event:
invariant( | kintone.events.AppRecordCreateSubmitSuccessEvent
destAttachmentField?.type === 'FILE', | kintone.events.AppRecordEditSubmitSuccessEvent
'The field type of destination attachment field code must be attachment field.', | kintone.events.MobileAppRecordCreateSubmitSuccessEvent
); | kintone.events.MobileAppRecordEditSubmitSuccessEvent,
const updateFileKeys: UpdateRecordAttachmentFieldValue = []; ) => {
if (lookupField.value !== '') { const context = await getPluginContext(event.appId, false);
const res = await client.record const mappings = filterConfigByPluginContext(loadPluginConfigLookup(PLUGIN_ID), context);
.getRecords({ if (mappings == null) {
app: lookupFieldProperty.lookup.relatedApp.app, return event;
query: `${lookupFieldProperty.lookup.relatedKeyField} = "${lookupField.value?.replace(/[\\"]/g, '\\$&')}"`, }
totalCount: true, const client = new KintoneRestAPIClient();
}) await Promise.all<void>(
.catch(() => null); mappings.map(async (mapping) => {
if (res != null && res.totalCount === '1') { const lookupField = event.record[mapping.lookupFieldCode];
const srcRecordId = res.records[0].$id; invariant(
invariant(srcRecordId.type === '__ID__', 'The field of Source record ID not found.'); lookupField?.type === 'NUMBER' || lookupField?.type === 'SINGLE_LINE_TEXT',
const srcAttachmentField = res.records[0][mapping.srcAttachmentFieldCode]; 'The field type of lookup field code must be number or single line text field.',
invariant( );
srcAttachmentField.type === 'FILE', const lookupFieldProperty = context.lookupFields.find((p) => p.code === mapping.lookupFieldCode);
'The field type of source attachment field code must be attachment field.', invariant(lookupFieldProperty != null, 'The property of lookup field not found.');
); const destAttachmentField = event.record[mapping.destAttachmentFieldCode];
destAttachmentField.value.forEach((destFileInfo) => { invariant(
if ( destAttachmentField?.type === 'FILE',
srcAttachmentField.value.find( 'The field type of destination attachment field code must be attachment field.',
(srcFileInfo) => );
destFileInfo.name === srcFileInfo.name && const updateFileKeys: UpdateRecordAttachmentFieldValue = [];
destFileInfo.size === srcFileInfo.size && if (lookupField.value !== '') {
destFileInfo.contentType === srcFileInfo.contentType, const res = await client.record
) != null .getRecords({
) { app: lookupFieldProperty.lookup.relatedApp.app,
updateFileKeys.push({ fileKey: destFileInfo.fileKey }); query: `${lookupFieldProperty.lookup.relatedKeyField} = "${lookupField.value?.replace(/[\\"]/g, '\\$&')}"`,
} totalCount: true,
}); })
await Promise.all<void>( .catch(() => null);
srcAttachmentField.value if (res != null && res.totalCount === '1') {
.filter((srcFileInfo) => { const srcRecordId = res.records[0].$id;
return ( invariant(srcRecordId.type === '__ID__', 'The field of Source record ID not found.');
destAttachmentField.value.find( const srcAttachmentField = res.records[0][mapping.srcAttachmentFieldCode];
(destFileInfo) => invariant(
destFileInfo.name === srcFileInfo.name && srcAttachmentField.type === 'FILE',
destFileInfo.size === srcFileInfo.size && 'The field type of source attachment field code must be attachment field.',
destFileInfo.contentType === srcFileInfo.contentType, );
) == null destAttachmentField.value.forEach((destFileInfo) => {
); if (
}) srcAttachmentField.value.find(
.map(async (srcFileInfo) => { (srcFileInfo) =>
return client.file destFileInfo.name === srcFileInfo.name &&
.downloadFile({ destFileInfo.size === srcFileInfo.size &&
fileKey: srcFileInfo.fileKey, destFileInfo.contentType === srcFileInfo.contentType,
}) ) != null
.then((fileData) => { ) {
return client.file.uploadFile({ updateFileKeys.push({ fileKey: destFileInfo.fileKey });
file: { }
name: srcFileInfo.name, });
data: new Blob([fileData], { type: srcFileInfo.contentType }), await Promise.all<void>(
}, srcAttachmentField.value
.filter((srcFileInfo) => {
return (
destAttachmentField.value.find(
(destFileInfo) =>
destFileInfo.name === srcFileInfo.name &&
destFileInfo.size === srcFileInfo.size &&
destFileInfo.contentType === srcFileInfo.contentType,
) == null
);
})
.map(async (srcFileInfo) => {
return client.file
.downloadFile({
fileKey: srcFileInfo.fileKey,
})
.then((fileData) => {
return client.file.uploadFile({
file: {
name: srcFileInfo.name,
data: new Blob([fileData], { type: srcFileInfo.contentType }),
},
});
})
.then((fileKey) => {
updateFileKeys.push(fileKey);
}); });
}) }),
.then((fileKey) => { );
updateFileKeys.push(fileKey); }
});
}),
);
} }
} if (
if ( destAttachmentField.value.length !== updateFileKeys.length ||
destAttachmentField.value.length !== updateFileKeys.length || destAttachmentField.value.every(
destAttachmentField.value.every( (v) =>
(v) => destAttachmentField.value.filter((e) => e.fileKey === v.fileKey).length !==
destAttachmentField.value.filter((e) => e.fileKey === v.fileKey).length !== updateFileKeys.filter((e) => e.fileKey === v.fileKey).length,
updateFileKeys.filter((e) => e.fileKey === v.fileKey).length, )
) ) {
) { await client.record.updateRecord({
await client.record.updateRecord({ app: event.appId,
app: event.appId, id: event.recordId,
id: event.recordId, record: {
record: { [mapping.destAttachmentFieldCode]: {
[mapping.destAttachmentFieldCode]: { value: updateFileKeys,
value: updateFileKeys, },
}, },
}, });
}); }
} }),
}), ).catch((e) => {
).catch((e) => { console.error(e);
console.log(e); });
}); await new Promise((resolve) => setTimeout(resolve, 10000));
return event; return event;
}, },
); );
})(kintone.$PLUGIN_ID);

View File

@@ -1,73 +1,28 @@
{ {
"compilerOptions": { "compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */ "lib": ["DOM", "ES2020"],
"jsx": "react-jsx",
"target": "ES2020",
"noEmit": true,
"skipLibCheck": true,
"useDefineForClassFields": true,
/* Basic Options */ /* modules */
// "incremental": true, /* Enable incremental compilation */ "module": "ESNext",
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "resolveJsonModule": true,
"module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ "moduleResolution": "bundler",
"lib": ["dom", "es2020"], /* Specify library files to be included in the compilation. */ "esModuleInterop": true,
// "allowJs": true, /* Allow javascript files to be compiled. */ "allowImportingTsExtensions": true,
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./plugin", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */ /* type checking */
"strict": true, /* Enable all strict type-checking options. */ "strict": true,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ "noUnusedLocals": true,
// "strictNullChecks": true, /* Enable strict null checks. */ "noUnusedParameters": true
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}, },
"include": [ "include": ["src/**/*", "./node_modules/@kintone/dts-gen/kintone.d.ts"],
"src/**/*", "ts-node": {
"./node_modules/@kintone/dts-gen/kintone.d.ts" "compilerOptions": {
] "module": "CommonJS"
}
}
} }