NewsResource.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 Filament\Forms\Components\Actions\Action;
  7. use Filament\Forms\Components\Group;
  8. use Filament\Forms\Components\Hidden;
  9. use Filament\Forms\Components\Repeater;
  10. use Filament\Forms\Components\RichEditor;
  11. use Filament\Forms\Components\Tabs;
  12. use Filament\Forms\Components\Tabs\Tab;
  13. use Filament\Forms\Components\TextInput;
  14. use Filament\Forms\Components\Textarea;
  15. use Filament\Forms\Components\Select;
  16. use Filament\Forms\Components\Radio;
  17. use Filament\Forms\Components\Section;
  18. use Filament\Forms\Components\Toggle;
  19. use Filament\Forms\Components\DatePicker;
  20. use Filament\Forms\Components\DateTimePicker;
  21. use Filament\Forms\Components\FileUpload;
  22. use Filament\Forms\Get;
  23. use Filament\Forms\Form;
  24. use Filament\Forms\Set;
  25. use Filament\Resources\Resource;
  26. use Filament\Tables;
  27. use Filament\Tables\Columns\IconColumn;
  28. use Filament\Tables\Columns\ImageColumn;
  29. use Filament\Tables\Columns\TextColumn;
  30. use Filament\Tables\Filters\SelectFilter;
  31. use Filament\Tables\Table;
  32. use Illuminate\Database\Eloquent\Builder;
  33. use Illuminate\Support\Facades\DB;
  34. use Illuminate\Support\Str;
  35. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  36. use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
  37. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  38. use RalphJSmit\Filament\SEO\SEO;
  39. use Illuminate\Support\HtmlString;
  40. class NewsResource extends Resource
  41. {
  42. protected static ?string $model = News::class;
  43. protected static ?string $modelLabel = "文章管理";
  44. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  45. protected static ?string $navigationGroup = '上稿內容管理';
  46. protected static ?string $navigationLabel = "文章管理";
  47. public static function form(Form $form): Form
  48. {
  49. return $form
  50. ->schema([
  51. //
  52. Section::make("新增 文章")->schema([
  53. Group::make()->schema([
  54. Select::make("news_category_id")
  55. ->options(NewsCategory::get()->pluck("name","id"))
  56. ->label("文章分類")
  57. ->columnSpan(1)
  58. ->native(false)
  59. ->afterStateHydrated(function ($component, $state) {
  60. // ✅ 如果沒有值,設定為第一項
  61. if (empty($state)) {
  62. $firstCategoryId = NewsCategory::first()?->id;
  63. if ($firstCategoryId) {
  64. $component->state($firstCategoryId);
  65. }
  66. }
  67. })
  68. ->required(),
  69. ])->columnSpanFull()->columns(2),
  70. Group::make()->schema([
  71. DatePicker::make('post_date')
  72. ->label("文章日期")
  73. ->closeOnDateSelection()->required(),
  74. DateTimePicker::make('start_date')
  75. ->label("預約發布時間")
  76. ->closeOnDateSelection(),
  77. DateTimePicker::make('end_date')
  78. ->label("預約下架時間")
  79. ->closeOnDateSelection(),
  80. ])->columnSpanFull()->columns(3),
  81. FileUpload::make('news_img_pc')->label("列表圖(desktop)")
  82. ->disk("public")
  83. // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
  84. ->directory("news"),
  85. FileUpload::make('news_img_mobile')->label("列表圖(mobile)")
  86. ->disk("public")
  87. // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
  88. ->directory("news"),
  89. Translate::make()->schema(fn (string $locale) => [
  90. TextInput::make('title')
  91. ->label("標題")
  92. ->reactive()
  93. ->afterStateHydrated(function ($state, callable $set) {
  94. $set('title_length', mb_strlen($state ?? ''));
  95. })
  96. ->afterStateUpdated(function ($state, callable $set) {
  97. $set('title_length', mb_strlen($state ?? ''));
  98. })
  99. ->helperText(function (callable $get) {
  100. $length = $get('title_length') ?? 0;
  101. $max = 24;
  102. $divClass = 'text-limit-amount';
  103. return new HtmlString("
  104. <div class='{$divClass} text-sm'>
  105. 目前字數:{$length} / {$max}
  106. </div>
  107. ");
  108. })
  109. ->columnSpan(1),
  110. TextInput::make('written_by')
  111. ->label("發佈者")->columnSpan(1),
  112. Textarea::make("description")
  113. ->rows(5)
  114. ->columnSpanFull()
  115. ->label("短文")
  116. ->reactive()
  117. ->afterStateHydrated(function ($state, callable $set) {
  118. $set('description_length', mb_strlen($state ?? ''));
  119. })
  120. ->afterStateUpdated(function ($state, callable $set) {
  121. $set('description_length', mb_strlen($state ?? ''));
  122. })
  123. ->helperText(function (callable $get) {
  124. $length = $get('description_length') ?? 0;
  125. $max = 84;
  126. $divClass = 'text-limit-amount';
  127. return new HtmlString("
  128. <div class='{$divClass} text-sm'>
  129. 目前字數:{$length} / {$max}
  130. </div>
  131. ");
  132. })
  133. ])->locales(["zh_TW", "en"])
  134. ->id("main")
  135. ->columnSpanFull()->columns(3),
  136. TextInput::make('order')->label("排序")->integer()->default(0),
  137. ])->columns(3),
  138. Section::make("SEO")->schema([
  139. // SEO::make(),
  140. Translate::make()->schema(fn (string $locale) => [
  141. TextInput::make('meta_title')->label("SEO 標題")->columnSpan(1),
  142. Textarea::make("meta_keyword")->rows(5)->columnSpanFull()->label("SEO 關鍵字"),
  143. Textarea::make("meta_description")->rows(5)->columnSpanFull()->label("SEO 短文"),
  144. ])
  145. ->locales(["zh_TW", "en"])
  146. ->id("seo"),
  147. FileUpload::make('meta_img')->label("放大預覽圖")->disk("public")
  148. // ->helperText('建議寬高限制為:1200*630px,檔案大小限制為1M以下')->maxSize('1024')
  149. ->directory("seo/news"),
  150. ])->columnSpanFull(),
  151. Section::make("文章內容")->schema([
  152. Repeater::make("paragraphs")->schema([
  153. TextInput::make('item_key')
  154. ->default(fn () => Str::random())
  155. ->hidden()
  156. ->afterStateHydrated(function (TextInput $component, $state) {
  157. if (empty($state)) {
  158. $component->state(Str::random());
  159. }
  160. }),
  161. Radio::make("paragraph_type")->options([
  162. 1 => "圖片",
  163. 2 => "文字",
  164. 3 => "影音",
  165. ])->label("")->default(1)->Live(),
  166. Group::make()->schema([
  167. Section::make('')->schema([
  168. Repeater::make("multiple_images")->schema([
  169. TextInput::make('para_img_item_key')
  170. ->default(fn () => Str::random())
  171. ->hidden()
  172. ->afterStateHydrated(function (TextInput $component, $state) {
  173. if (empty($state)) {
  174. $component->state(Str::random());
  175. }
  176. }),
  177. Translate::make()->schema(fn (string $locale) => [
  178. TextInput::make('image_alt')->label("圖片註文"),
  179. ])->locales(["zh_TW", "en"])
  180. ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
  181. FileUpload::make('image_url')->label("")->disk("public")
  182. // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
  183. ->directory("news/extraPhoto")
  184. ->maxFiles(10),
  185. ])
  186. ->relationship("photos")
  187. ->label("")
  188. ->orderColumn('order')
  189. ])
  190. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
  191. Group::make()->schema([
  192. FilamentLexicalEditor::make('text_content_tw')
  193. ->label('繁體中文內容')
  194. ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
  195. ->enabledToolbars([
  196. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  197. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  198. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  199. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  200. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  201. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  202. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR, ToolbarItem::FONT_FAMILY
  203. ])
  204. ->live(onBlur: true)
  205. ->columnSpanFull(),
  206. FilamentLexicalEditor::make('text_content_en')
  207. ->label('English Content')
  208. ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
  209. ->enabledToolbars([
  210. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  211. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  212. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  213. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  214. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  215. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  216. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR, ToolbarItem::FONT_FAMILY
  217. ])
  218. ->columnSpanFull(),
  219. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
  220. Group::make()->schema([
  221. Section::make("")->schema([
  222. FileUpload::make('video_img')->label("影片底圖")
  223. ->disk("public")
  224. ->directory("news/paragraph/video"),
  225. // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
  226. Translate::make()->schema(fn (string $locale) => [
  227. TextInput::make('video_img_alt')->label("圖片註文")->columnSpan(1),
  228. ])->locales(["zh_TW", "en"])
  229. ->id(fn ($get) => "para_video_img_alt_" . $get('item_key')),
  230. Radio::make("video_type")->label("")->options([
  231. 1 => "網址",
  232. 2 => "檔案"
  233. ])->columnSpanFull()->default(1)->Live(),
  234. Group::make()->schema([
  235. TextInput::make('link')->label("網址")->nullable(),
  236. ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
  237. Group::make()->schema([
  238. FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
  239. // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
  240. // ->maxSize(102400)
  241. ->nullable(),
  242. ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
  243. ]),
  244. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
  245. ])
  246. ->relationship("paragraphs")
  247. ->label("段落")
  248. ->collapsible()
  249. ->reorderableWithButtons()
  250. ->orderColumn('order')
  251. ->cloneable()
  252. ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
  253. if ($data['paragraph_type'] == 2 && !empty($data['text_content'])) {
  254. $content = is_string($data['text_content'])
  255. ? json_decode($data['text_content'], true)
  256. : $data['text_content'];
  257. if (is_array($content)) {
  258. $data['text_content_tw'] = $content['zh_TW'] ?? '';
  259. $data['text_content_en'] = $content['en'] ?? '';
  260. }
  261. }
  262. return $data;
  263. })
  264. ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array{
  265. if ($data['paragraph_type'] == 2) {
  266. $data["text_content"] = ["zh_TW" => $data["text_content_tw"], "en" => $data["text_content_en"]];
  267. // 移除臨時的分離欄位,只保留合併的 JSON 欄位
  268. unset($data['text_content_tw']);
  269. unset($data['text_content_en']);
  270. }
  271. return $data;
  272. })
  273. ]),
  274. ]);
  275. }
  276. public static function table(Table $table): Table
  277. {
  278. $url = env('APP_URL')=="https://webdev.yico.tw:8088/" ? "https://demo.blockstudio.tw/yichiu/zh/news/" : "https://www.yico.tw/" ;
  279. return $table
  280. ->columns([
  281. //
  282. TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
  283. TextColumn::make("title")->label("標題")->alignCenter(),
  284. TextColumn::make("written_by")->label("發佈者")->alignCenter(),
  285. TextColumn::make("post_date")->label("文章時間")->dateTime('Y/m/d')->alignCenter(),
  286. ImageColumn::make("news_img_pc_url")->label("列表圖")->alignCenter(),
  287. TextColumn::make("list_audit_state")->label("狀態")->badge()
  288. ->color(fn (string $state): string => match ($state) {
  289. '暫存' => 'warning',
  290. '已發佈' => 'success',
  291. }),
  292. IconColumn::make("on_top")->label("置頂")
  293. ->color(fn (string $state): string => match ($state) {
  294. 1 => 'success',
  295. default => ''
  296. })
  297. ->icon(fn (string $state): string => match ($state) {
  298. 1 => 'heroicon-o-check-circle',
  299. default => ''
  300. })
  301. ->action(function ($record): void {
  302. $record->on_top = !$record->on_top;
  303. $record->save();
  304. }),
  305. TextColumn::make("start_date")->label("預計發佈時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  306. TextColumn::make("end_date")->label("預計下架時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  307. TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  308. TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
  309. ])
  310. ->filters([
  311. SelectFilter::make('news_category_id')->label("分類")
  312. ->options(NewsCategory::orderBy("order")->pluck("name", "id"))
  313. ->attribute('news_category_id'),
  314. SelectFilter::make('post_date')->label("年份")
  315. ->options(News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull("post_date")->distinct()->pluck("year","year")->toArray())
  316. ->query(
  317. fn (array $data, Builder $query): Builder =>
  318. $query->when(
  319. $data['value'],
  320. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value']. "%")
  321. )
  322. ),
  323. SelectFilter::make('visible')->label("狀態")
  324. ->options([
  325. 0 => "暫存",
  326. 1 => "已發佈",
  327. ])
  328. ->query(
  329. fn (array $data, Builder $query): Builder =>
  330. $query->when(
  331. $data['value'],
  332. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  333. )
  334. ),
  335. ])
  336. ->actions([
  337. Tables\Actions\EditAction::make(),
  338. Tables\Actions\DeleteAction::make(),
  339. \Filament\Tables\Actions\Action::make("audit")
  340. ->label(fn ($record) => match ($record->visible) {
  341. 0 => '發佈',
  342. 1 => '下架',
  343. })
  344. ->color(fn ($record) => match ($record->visible) {
  345. 0 => 'warning',
  346. 1 => 'gray',
  347. })
  348. ->icon(fn ($record) => match ($record->visible) {
  349. 0 => 'heroicon-m-chevron-double-up',
  350. 1 => 'heroicon-m-chevron-double-down',
  351. })
  352. ->action(function ($record): void {
  353. $record->visible = !$record->visible;
  354. $record->save();
  355. })
  356. ->outlined()
  357. ->requiresConfirmation(),
  358. Tables\Actions\Action::make('preview')
  359. ->label('前台預覽')
  360. ->icon('heroicon-m-arrow-top-right-on-square')
  361. ->color('info')
  362. ->url(fn ($record) => $url.$record->id."?preview=true")
  363. ->openUrlInNewTab()
  364. ->outlined(),
  365. ])
  366. ->bulkActions([
  367. Tables\Actions\BulkActionGroup::make([
  368. Tables\Actions\DeleteBulkAction::make(),
  369. ]),
  370. ])
  371. ->defaultSort('order', 'desc')
  372. ->defaultSort('created_at', 'desc');
  373. }
  374. public static function getRelations(): array
  375. {
  376. return [
  377. //
  378. ];
  379. }
  380. public static function getPages(): array
  381. {
  382. return [
  383. 'index' => Pages\ListNews::route('/'),
  384. 'create' => Pages\CreateNews::route('/create'),
  385. 'edit' => Pages\EditNews::route('/{record}/edit'),
  386. 'view' => Pages\ViewNews::route('/{record}/view'),
  387. ];
  388. }
  389. }