123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use App\Service\DeepLService;
  7. use Filament\Forms\Components\DatePicker;
  8. use Filament\Forms\Components\FileUpload;
  9. use Filament\Forms\Components\Group;
  10. use Filament\Forms\Components\Radio;
  11. use Filament\Forms\Components\Repeater;
  12. use Filament\Forms\Components\RichEditor;
  13. use Filament\Forms\Components\Section;
  14. use Filament\Forms\Components\Select;
  15. use Filament\Forms\Components\Tabs;
  16. use Filament\Forms\Components\Tabs\Tab;
  17. use Filament\Forms\Components\Textarea;
  18. use Filament\Forms\Components\TextInput;
  19. use Filament\Forms\Form;
  20. use Filament\Forms\Get;
  21. use Filament\Resources\Resource;
  22. use Filament\Tables;
  23. use Filament\Tables\Columns\IconColumn;
  24. use Filament\Tables\Columns\ImageColumn;
  25. use Filament\Tables\Columns\TextColumn;
  26. use Filament\Tables\Filters\SelectFilter;
  27. use Filament\Tables\Table;
  28. use Illuminate\Database\Eloquent\Builder;
  29. use Illuminate\Support\Str;
  30. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  31. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  32. class NewsResource extends Resource
  33. {
  34. protected static ?string $model = News::class;
  35. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  36. protected static ?string $navigationLabel = '最新消息管理';
  37. protected static ?string $navigationGroup = '最新消息';
  38. protected static ?string $modelLabel = '最新消息管理';
  39. protected static ?int $navigationSort = 3;
  40. public static function form(Form $form): Form
  41. {
  42. $editor_toolbar = [
  43. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  44. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  45. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  46. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  47. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  48. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  49. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR,
  50. ];
  51. return $form
  52. ->schema([
  53. //
  54. Tabs::make()->schema([
  55. Tab::make('基本資訊')->schema([
  56. Select::make('news_category_id')->label('分類')->options(function () {
  57. return NewsCategory::pluck('name', 'id');
  58. })->required()
  59. ->columnSpan(1),
  60. DatePicker::make('post_date')->label('發佈日')
  61. ->native(false)
  62. ->closeOnDateSelection()
  63. ->required()
  64. ->columnSpan(1),
  65. Translate::make()->schema(fn (string $locale) => [
  66. TextInput::make('title')->required($locale == 'zh_TW')->label('標題')->columnSpan(1),
  67. TextInput::make('written_by')->required($locale == 'zh_TW')->label('撰文者')->columnSpan(1),
  68. Textarea::make('description')->required($locale == 'zh_TW')->label('簡述')->columnSpan(2),
  69. ])
  70. ->locales(['zh_TW', 'en'])
  71. ->actions([
  72. app(DeepLService::class)->createTranslationAction('Main', ['title', 'written_by', 'description']),
  73. ])->columns(2)
  74. ->columnSpan(2)
  75. ->id('Main-content'),
  76. FileUpload::make('news_img')->label('圖片')
  77. ->image()
  78. ->optimize('webp')
  79. ->directory('news')
  80. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor()
  81. ->columnSpan(2),
  82. Translate::make()->schema(fn (string $locale) => [
  83. TextInput::make('news_img_alt')->label('圖片註釋'),
  84. ])
  85. ->locales(['zh_TW', 'en'])
  86. ->actions([
  87. app(DeepLService::class)->createTranslationAction('NewsImageAlt', ['news_img_alt']),
  88. ])->columnSpan(2)
  89. ->id('Main-alt'),
  90. ])->columns(2),
  91. Tab::make('SEO')->schema([
  92. Translate::make()->schema(fn (string $locale) => [
  93. TextInput::make('meta_title')->label('SEO 標題'),
  94. TextInput::make('meta_keyword')->label('SEO 關鍵字'),
  95. Textarea::make('meta_description')->label('SEO 簡述'),
  96. ])
  97. ->locales(['zh_TW', 'en'])
  98. ->actions([
  99. app(DeepLService::class)->createTranslationAction('Seo', ['meta_title', 'meta_keyword', 'meta_description']),
  100. ])->columnSpanFull(),
  101. FileUpload::make('meta_img')->label('放大預覽圖')
  102. ->image()
  103. ->optimize('webp')
  104. ->directory('news/seo')
  105. ->columnSpan(1)
  106. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->imageEditor()
  107. ->id('Seo'),
  108. ]),
  109. Tab::make('內文編輯')->schema([
  110. Repeater::make('paragraphs')->schema([
  111. TextInput::make('item_key')
  112. ->default(fn () => Str::random())
  113. ->hidden()
  114. ->afterStateHydrated(function (TextInput $component, $state) {
  115. if (empty($state)) {
  116. $component->state(Str::random());
  117. }
  118. }),
  119. Radio::make('paragraph_type')->options([
  120. 1 => '圖片',
  121. 2 => '文字',
  122. // 3 => "影音"
  123. ])->label('')->inline()->default(1)->Live(),
  124. Group::make()->schema([
  125. Section::make('')->schema([
  126. FileUpload::make('img_url')->label('')->directory('news/paragraphs')
  127. ->image()
  128. ->optimize('webp')
  129. ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
  130. Translate::make()->schema(fn (string $locale) => [
  131. TextInput::make('img_alt')->label('圖片註釋'),
  132. ])
  133. ->locales(['zh_TW', 'en'])
  134. ->actions([
  135. app(DeepLService::class)->createTranslationAction('ParagraphImgAlt', ['img_alt']),
  136. ])->columnSpan(1)
  137. ->id(fn ($get) => 'para_img_'.$get('item_key')),
  138. ]),
  139. ])->visible(fn (Get $get): bool => $get('paragraph_type') == 1),
  140. Group::make()->schema([
  141. Translate::make()->schema(fn (string $locale) => [
  142. RichEditor::make('text_content')
  143. ->toolbarButtons([
  144. 'blockquote',
  145. 'bold',
  146. 'bulletList',
  147. 'h2',
  148. 'h3',
  149. 'italic',
  150. 'link',
  151. 'orderedList',
  152. 'redo',
  153. 'strike',
  154. 'underline',
  155. 'undo',
  156. ])
  157. ->disableToolbarButtons([
  158. 'blockquote',
  159. 'strike',
  160. 'attachFiles',
  161. ])
  162. ->fileAttachmentsDisk('s3')
  163. ->fileAttachmentsDirectory('attachments')
  164. ->fileAttachmentsVisibility('private'),
  165. ])
  166. ->locales(['zh_TW', 'en'])
  167. ->actions([
  168. app(DeepLService::class)->createTranslationAction('ParagraphText', ['text_content']),
  169. ])->columnSpan(1)
  170. ->id(fn ($get) => 'para_text_'.$get('item_key')),
  171. ])->visible(fn (Get $get): bool => $get('paragraph_type') == 2),
  172. ])
  173. ->relationship('paragraphs')
  174. ->label('段落')
  175. ->collapsible()
  176. ->reorderableWithButtons()
  177. ->orderColumn('order')
  178. ->cloneable(),
  179. ]),
  180. ])->columnSpanFull(),
  181. ]);
  182. }
  183. public static function table(Table $table): Table
  184. {
  185. return $table
  186. ->columns([
  187. //
  188. TextColumn::make('newsCategory.name')->label('分類')->alignCenter(),
  189. TextColumn::make('title')->label('標題')->alignCenter(),
  190. TextColumn::make('written_by')->label('發佈者')->alignCenter(),
  191. TextColumn::make('post_date')->label('發佈時間')->dateTime('Y/m/d')->alignCenter(),
  192. ImageColumn::make('news_img')->label('列表圖')->alignCenter(),
  193. TextColumn::make('list_audit_state')->label('狀態')->badge()
  194. ->color(fn (string $state): string => match ($state) {
  195. '暫存' => 'warning',
  196. '已發佈' => 'success',
  197. }),
  198. IconColumn::make('on_top')->label('置頂')
  199. ->color(fn (string $state): string => match ($state) {
  200. 1 => 'success',
  201. default => ''
  202. })
  203. ->icon(fn (string $state): string => match ($state) {
  204. 1 => 'heroicon-o-check-circle',
  205. default => ''
  206. })
  207. ->action(function ($record): void {
  208. $record->on_top = ! $record->on_top;
  209. $record->save();
  210. }),
  211. TextColumn::make('created_at')->label('建立時間')->dateTime('Y/m/d H:i:s')->alignCenter(),
  212. TextColumn::make('updated_at')->label('更新時間')->dateTime()->alignCenter(),
  213. ])
  214. ->filters([
  215. SelectFilter::make('news_category_id')->label('分類')
  216. ->options(NewsCategory::orderBy('order')->pluck('name', 'id'))
  217. ->attribute('news_category_id'),
  218. SelectFilter::make('post_date')->label('年份')
  219. ->options(News::select(\DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull('post_date')->distinct()->pluck('year', 'year')->toArray())
  220. ->query(
  221. fn (array $data, Builder $query): Builder => $query->when(
  222. $data['value'],
  223. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value'].'%')
  224. )
  225. ),
  226. SelectFilter::make('visible')->label('狀態')
  227. ->options([
  228. 0 => '暫存',
  229. 1 => '已發佈',
  230. ])
  231. ->query(
  232. fn (array $data, Builder $query): Builder => $query->when(
  233. $data['value'],
  234. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  235. )
  236. ),
  237. ])
  238. ->actions([
  239. Tables\Actions\EditAction::make(),
  240. Tables\Actions\DeleteAction::make(),
  241. \Filament\Tables\Actions\Action::make('audit')
  242. ->label(fn ($record) => match ($record->visible) {
  243. 0 => '發佈',
  244. 1 => '下架',
  245. })
  246. ->color(fn ($record) => match ($record->visible) {
  247. 0 => 'warning',
  248. 1 => 'gray',
  249. })
  250. ->icon(fn ($record) => match ($record->visible) {
  251. 0 => 'heroicon-m-chevron-double-up',
  252. 1 => 'heroicon-m-chevron-double-down',
  253. })
  254. ->action(function ($record): void {
  255. $record->visible = ! $record->visible;
  256. $record->save();
  257. })
  258. ->outlined()
  259. ->requiresConfirmation(),
  260. ])
  261. ->bulkActions([
  262. Tables\Actions\BulkActionGroup::make([
  263. Tables\Actions\DeleteBulkAction::make(),
  264. ]),
  265. ])
  266. ->reorderable('order')
  267. ->defaultSort('order');
  268. }
  269. public static function getRelations(): array
  270. {
  271. return [
  272. //
  273. ];
  274. }
  275. public static function getPages(): array
  276. {
  277. return [
  278. 'index' => Pages\ListNews::route('/'),
  279. 'create' => Pages\CreateNews::route('/create'),
  280. 'edit' => Pages\EditNews::route('/{record}/edit'),
  281. ];
  282. }
  283. }